How to mass change Canonical URLs using Yoast SEO in WordPress

0

You might want to set all or some of canonical urls in WordPress. With Yoast SEO, you can change canonical urls for single posts respectively. You can also use the wpseo_canonical filter to change canonical urls.

For example, if you want to change all canonical urls for single posts by changing the site's domain name (to example.com), you can add the following code to your theme's function file:

// Batch Change Canonical URLs
function change_canonical($url) {
    global $post;

    if ( is_singular( 'post' ) ) {
         return 'https://example.com/' . $post->post_name;
    } else {
         return $url;
    }
}
add_filter( 'wpseo_canonical', 'change_canonical' ); 

Now you can see that canonical urls have been changed as you expected:

Mass change canonical urls

You can disable canonical urls by adding the following code:

add_filter( 'wpseo_canonical', '__return_false' );

If you want to add canonical urls without using a plugin, you can add the following line to the head of your WordPress theme template:

<link rel="canonical" href="https://example.com<?php echo $_SERVER['REQUEST_URI'];?>">

It's important to set canonical urls correctly for SEO. Yoast SEO, which is used by over 5 million users, is a good SEO plugin to help you make your site SEO-optimized.

You can also use other SEO plugins such as All in One SEO Pack. Personally, I prefer Yoast SEO which enables users to fine-tune SEO.