How to add Canonical URLs without using a WordPress Plugin

What is a canonical URL?

A canonical URL is an HTML element that helps prevent duplicate content issues by telling search engines which version of a page to take into account when indexing your website.

Search engines face problems determining the original source for documents that are available on multiple URLs. You can help search engines using the rel=”canonical” when you have pages with similar content.

Content duplication can happen in many ways, like:

  • Duplication due to GET-parameters( Ex: Search engines consider https://wpartisan.net/quick-tips/how-to-add-canonical-urls-without-using-a-wordpress-plugin/ and https://wpartisan.net/quick-tips/how-to-add-canonical-urls-without-using-a-wordpress-plugin/?paramenter=1 entirely different URL. )
  • Duplication due to with or without WWW in the URL.
  • Duplication due to HTTP and HTTPS protocols( Ex: Search engines consider https://wpartisan.net/quick-tips/how-to-add-canonical-urls-without-using-a-wordpress-plugin/ and http://wpartisan.net/quick-tips/how-to-add-canonical-urls-without-using-a-wordpress-plugin/ entirely different URL. )

How to add in WordPress?

// You can add just editing your header.php file( inside <head></head> section ) like:

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

// You need to replace https://wpartisan.net with your domain name

We can also add this using wp_head action hook like the one below:

add_action('wp_head', 'add_canonical');
function add_canonical(){
echo '<link rel="canonical" href="https://wpartisan.net'.$_SERVER['REQUEST_URI'].'" />';
// You need to replace https://wpartisan.net with your domain name
}

Leave a Reply

Your email address will not be published. Required fields are marked *