Learn how to change Yoast SEO canonical url for your complete wordpress website. For that we will create a plugin which will add_filter for wpseo_canonical property and replace the existing url with the new url.
<?php
/*
* Plugin Name: Change Canonical URL
* Plugin URI: https://akashmittal.com
* Description: Changes canonical url domain.
* Author: Akash
* Version: 1.0
* Author URI: https://akashmittal.com
*
**/
add_filter('wpseo_canonical', 'change_yoastseo_canonical_url');
function change_yoastseo_canonical_url($url){
$new_domain = 'akashmittal.com'; // change it with your main domain
$url_info = parse_url(home_url());
$old_domain = $url_info['host'];
return str_replace($old_domain, $new_domain, $url);
}
Steps to Create Plugin
Use these steps to create your plugin –
- Create a folder on desktop and name it
change_yoast_seo_canonical_url - Inside this folder, create a php script –
change_yoast_seo_canonical_url.php - Copy the provided code into this php file and save it.
- Zip the whole folder.
- Open
Add New Pluginpage in your wordpress dashboard and upload this zip folder. - Activate the plugin.
- Test by opening a website page and check page source. You canonical url should be replaced.
Why you may need to replace canonical urls?
There are multiple reasons. In my case I was running wordpress on a subdomain but generating static website for production. Now Google was also crawling my subdomain and listing it’s urls in the search.
I couldn’t mark my website uncrawlable because that would have generated static website with no-index meta tags. So, I decided to change all the canonical urls to main domain.