How do I add canonical tags to WordPress category/archive pages?

by chasity.halvorson , in category: SEO , 7 months ago

How do I add canonical tags to WordPress category/archive pages?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by percy_bauch , 7 months ago

@chasity.halvorson 

There are several ways to add canonical tags to WordPress category/archive pages:

  1. Using a plugin: One of the easiest ways to add canonical tags to WordPress is by using a plugin such as Yoast SEO or All in One SEO Pack. Simply install the plugin, and then navigate to the plugin's settings. From there, you can configure the canonical tags for your category and archive pages.
  2. Manually adding the code: You can also manually add the code for the canonical tags to the header.php file of your WordPress theme. To do this, open the header.php file and paste the following code just before the closing </head> tag:
1
2
3
<?php if (is_category()) { ?>
<link rel="canonical" href="<?php echo get_permalink( $post->post_parent ); ?>" />
<?php } ?>


This code will set the canonical tag for your category pages to the parent page.

  1. Using a function: If you prefer to use a function, you can add the following code to your theme's functions.php file:
1
2
3
4
5
6
function add_canonical_tags() {
    if (is_category()) {
        echo '<link rel="canonical" href="' . get_permalink( $post->post_parent ) . '" />';
    }
}
add_action('wp_head', 'add_canonical_tags');


This code will set the canonical tag for your category pages to the parent page.


Whichever method you choose, be sure to test your website after making the changes to make sure that the canonical tags are being added correctly.