Hello,
Thank you for contacting Rank Math and bringing your concern to our attention. I’m sorry for any inconvenience this issue may have caused you.
You can use and customize this filter on your site to change the canonical URL:
https://rankmath.com/kb/filters-hooks-api-developer/#change-canonical-url
Here’s a sample code to set the self-referencing canonical URL:
add_filter( 'rank_math/frontend/canonical', function( $canonical ) {
$canonical = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
return $canonical;
});
Hope that helps.
Thank you.
Hey,
Thanks for your answer.
I don’t get it. I’ve read the article which you refer to, but I can’t get it right in my functions.php file.
Which rules I need to adjust to set a custom URL as canonical URL?
Hope you can help me.
Hello,
The filter shared by my colleague above adds self-referencing canonical for any URL of your site.
You may modify the output of the variable $canonical to change the output of canonical URL.
Hope that helps, and please do not hesitate to let us know if you need our assistance with anything else.
Thank you.
Hello,
Yes. I understand that I can set a custom Canonical URL. But what I don’t get is the URL on which I want to set the custom canonical. So I know I need to use the following code:
/**
* Allow changing of the canonical URL.
*
* @param string $canonical The canonical URL.
*/
add_filter( 'rank_math/frontend/canonical', function( $canonical ) {
return $canonical;
});
But what do I need to add/change to say on which URL this canonical has to be used?
Regards.
Hello,
As far as I understood, you’re looking for the following one:
add_filter( 'rank_math/frontend/canonical', function( $canonical ) {
global $post;
$ids = array(1,2,3); // Replace 1,2,3 with your post ID/ID(s) where you would like to apply the filter
if(!empty($post->ID) && is_numeric($post->ID) && in_array((int)$post->ID, $ids)){
$canonical = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; //your custom canonical URL here.
}
return $canonical;
});
Let us know if it’s working for you.
Thank you.
Hello,
Since we did not hear back from you for 15 days, we are assuming that you found the solution. We are closing this support ticket.
If you still need assistance or any other help, please feel free to open a new support ticket, and we will be more than happy to assist.
Thank you.