How do I add canonical tags to WordPress category/archive pages?
@chasity.halvorson
There are several ways to add canonical tags to WordPress category/archive pages:
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 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.
@chasity.halvorson
It is important to note that before making any changes to your theme files or adding any code, it is recommended to create a backup of your website.
Also, consider the following:
1 2 3 |
<?php if (is_category()) { ?> <link rel="canonical" href="<?php echo get_permalink( $post->post_parent ); ?>" /> <?php } ?> |
Save the changes and re-upload the edited header.php file to your server.
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'); |
Save the changes and re-upload the updated functions.php file to your server.
Remember to clear any caching plugins or server caching after making these changes to ensure the canonical tags are being displayed correctly.
It is also worth mentioning that canonical tags are essential for avoiding duplicate content issues and providing search engines with a preferred version of your content. Make sure to set the canonical URL appropriately to avoid any negative impact on your website's SEO.