Change Yoast SEO Canonical URL for Complete Website WordPress

Total
0
Shares
change yoast seo canonical url for complete website in wordpress

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 –

  1. Create a folder on desktop and name it change_yoast_seo_canonical_url
  2. Inside this folder, create a php script – change_yoast_seo_canonical_url.php
  3. Copy the provided code into this php file and save it.
  4. Zip the whole folder.
  5. Open Add New Plugin page in your wordpress dashboard and upload this zip folder.
  6. Activate the plugin.
  7. 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.