Canonical URLs without using a WordPress Plugin

Universal PHP Code for Canonical URLS

Below is the code that you need to add within the head of your theme template:

<link rel="canonical" href="<?php echo $_SERVER['REQUEST_URI'];?>">

The above code will be added to all pages, it will protect you from duplicates from www/non-www, https/http, shortlinks and query strings suffix, this is because of your www/non-www, domain and protocol are hard set, the PHP command $_SERVER[‘REQUEST_URI’] will return the relative url and suffix it to the end of your URL and therefore make a absolute URL.

It will be used on catagories, tags, author, indexes and achieves, these pages are not considered as duplicate by Google or Bing because snippets of various pages on one page is a unique combination.

The only reason I can think of when you should NOT use canonical links on those pages is when you are displaying full articles on those pages without any other articles on the same page, therefore this would be considered duplicate. I do however recommend for UX purposes (User Experience) that you do not use this format in any case.

Not Recommended Method

If for some mad reason you would prefer not to use canonical on categories, tags, author, indexes and achieves pages then you can use the code below:

    // For most people this method should be avoided... use the one above!
    if(is_singular()) {
        // Canonicals used on Posts and Pages Only!
        echo '<link rel="canonical" href="' . $_SERVER['REQUEST_URI'] . '">';
    } else {
        // Do Nothing!

Adding canonical Links in WordPress

Below are a few easy steps that will have you up and running with WordPress canonical URLs in no time at all, and without a plugin.

  1. Login to WordPress
  2. Hover over Appearance
  3. Click Editor
  4. Find Theme Header (header.php)
  5. Add the Universal PHP Code for Canonical URLS found above within the HEAD section of your theme header file.

credit: Simon Hayter

svg2 min read
Subscribe & Follow
Trending Now