Hello,
To change the canonical tag of all URLs without affecting other structured data elements, you can use the following code snippet in your functions.php
file:
function custom_change_canonical_url( $canonical_url ) {
// Replace 'https://rankmath.com/kb/how-to-change-canonical-url/' with your new domain
$new_canonical_url = 'https://rankmath.com/kb/how-to-change-canonical-url/' . $_SERVER['REQUEST_URI'];
return $new_canonical_url;
}
add_filter( 'rank_math/frontend/canonical', 'custom_change_canonical_url' );
This code snippet hooks into Rank Math’s filter to modify the canonical URL without affecting other structured data elements. Make sure to replace 'https://rankmath.com/kb/how-to-change-canonical-url/'
with your actual new domain.
If you encounter any issues or need further assistance, please let us know.
Thank you for reaching out!
Sources:
Alternate Page with Proper Canonical Tag Status in Google Search Console » Rank Math
Setting Canonical URLs in Rank Math » Rank Math
How to Fix ‘Duplicate Without User-Selected Canonical’ Status in Google Search Console » Rank Math
Hello,
I have updated the sensitive data as requested. Can you please check further?
Thank you.
Hello,
Thank you for contacting Rank Math support.
You will also have to modify and use the following filter to keep the OG URL self-referencing after changing the canonical URL:
add_filter( 'rank_math/opengraph/url', function( $url ) {
return $url;
});
The URL in Schema will use the canonical URL. However, since Google will not index the page if it has the canonical tag pointing to a different URL, the URL in Schema doesn’t matter. You can ignore it, as it isn’t going to cause any issues.
Please do not hesitate to let us know if you need our assistance with anything else.
I do not want urls in schema and meta og:url to change. I just want to change canonical url
Hello,
After applying the filter for the canonical URL, you can use to following filter to make sure the og:url
doesn’t change:
add_filter( 'rank_math/opengraph/url', function( $url ) {
global $wp;
$current_slug = home_url( $wp->request );
$url = $current_slug;
return $url;
});
Regarding the URLs on schema, it doesn’t matter even if you’re using any schema or not because Google is not going to index these pages for a different canonical URL. So, if you want, you can also disable the Schema module for your old domain.
Hope that helps and please don’t hesitate to let us know if you have any other questions.
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.