1

I have some dynamic templates where I have to customize the canonical links.

According to Yoast documentation the hook to use is wpseo_canonical

I have two functions pointing to different pages IDs:

add_filter('wpseo_canonical', 'listpagecanonical');
function listpagecanonical($string) {
    if (is_page(1)){
        //I do my stuff here
        return 'http://canonicalurl.com'
    }
}

Then I have another:

add_filter('wpseo_canonical', 'detailpagecanonical');
function detailpagecanonical($string) {
   if (is_page(2)){
       //I do my stuff here
       return 'http://canonicalurl2.com'
   }
}

The problem I'm having is that if both filters have the same priority, like the example, they simply don't work, if I add 10, 1 to the first it will work but 2nd wont. If I add 20, 1 to second, it will work but first will stop working and so on.

Is there any way to do this in a way that they don't override themselves like that?

Thanks.

  • Why do you run two separate filter functions when you can just run one with a conditional statement to choose between pages – Pieter Goosen Sep 9 '15 at 15:58
  • Hi Pieter, thanks for your comment. I have like that because I have several customizations like this and the function name points to the specific thing I'm doing the function for, this way they will be easier to recognize and maintain. If they are all together then it will be harder to find what ID corresponds to each one of the templates. – Jaypee Sep 9 '15 at 16:00
  • Thanks for the update Pieter, it really sucks to have a correct answer vanishes like that. Let me know what they say. – Jaypee Sep 9 '15 at 18:10
  • OK, sorted, although the answer got downvotes twice. I have added extra meat to the bone and upvoted it. I have also rolled back your edit as the problem was solved. Enjoy ;-) – Pieter Goosen Sep 9 '15 at 18:46
  • Thank you man! Why the downvotes though, it might be a silly question but the answer is the correct...weird. Thanks anyways. – Jaypee Sep 9 '15 at 19:54
3

Filters should be returned even if your condition fails. You are currently just returning the output when your condition is met, not when it fails.

return $string; at the end of each function should solve your issue.

EXAMPLE

add_filter('wpseo_canonical', 'listpagecanonical');
function listpagecanonical($string) {
    if (is_page(1)){
        //I do my stuff here
        return 'http://canonicalurl.com'
    }
    return $string;
}
  • It would improve answer a lot to explain why does that matter. – Rarst Sep 9 '15 at 18:37
2

The problem is that in filter you should always return a value. If you don't have to change the value being passed, then you should return it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.