WordPress Canonical URLs with HTTP or HTTPS per Post/Page

These are basic instructions on how you can define the WordPress canonical URL for each post or page to use either the http or https protocol — without plugins.

Also known as; conditional canonical URLs.

Canonical URLs HTTP HTTPS

In this way — you can tell Google which protocol version of each page of your website to index; with mixed http and https pages as you like.

See this post for instructions on hosting WordPress on both http/https.

This requires the use of a WordPress child theme — and then copy over header.php for editing and also functions.php will require some code obviously.

Step 1. Define canonical content in functions.php

Use the below code to create a function with a list of post/page IDs — for which you can define either http or https to be set as the canonical URL.

function httporhttps_function() {
if ( is_single( array(1, 2, 3, 4))) { return 'http'; }
elseif ( is_page( array(5, 6, 7, 8))) { return 'http'; }
elseif ( is_front_page()) { return 'https'; }
else { return 'https'; }
}

Also front page can be defined in this example (for static front pages see below). If the viewed content is anything else the last definition will be used.

Step 2. Remove WordPress default canonical URL

By default WordPress includes a canonical in the content which changes to http or https automatically depending on which version the visitor is on.

You will first need to remove this feature by placing the following code just before where it says <?php wp_head(); ?> in header.php:

<?php remove_action('wp_head', 'rel_canonical'); ?>

Step 3. Add your own conditional canonical URL

Place this in the head section of header.php:

<link rel="canonical" href="<?php echo httporhttps_function(); ?>://www.yourdomain.com<?php echo $_SERVER['REQUEST_URI'];?>">

Obviously place the domain URL with your own.

Please note:

For a static front page — get the ID by going to your database with phpMyAdmin and look for the page_on_front value under option_name; it will display the ID number.

I haven’t included categories, archives and other such pages in this examples — for those please see all the available conditional tags for WordPress.

Hope this was helpful and would love to hear your comments about this!
Kindest regards, Tim.

Leave a Comment