Add A Canonical Link To Your WordPress Header

WordPress doesn’t generate a <link rel=”canonical” href=”http://www.yoursite.com”> by default.

This can cause issues with Google not indexing your page or indexing an incorrect canonical URL. You can get around this by adding your own canonical link to your site.

In order to do so, ensure you have created a child theme (see here on how to create your own WordPress child theme)

You’ll then need to copy the “header.php” file from the parent theme into your child theme’s folder and add the following code just before the <?php wp_head()?> code:


/** Add Canonical Tag **/
        $current_term = '';
	$canonical_url = '';

	if ( is_front_page() && is_main_query() ) 
	{
        /** We're On The Home Page **/
		$canonical_url = site_url();
	}
	elseif (is_category()) 
	{
        /** We're On A Category Page **/
		$current_term = get_queried_object();

		if ($current_term) 
		{
		  $canonical_url = get_term_link( $current_term );
		}
	}
	else
	{
        /** We're on a Post or Page **/
		 $canonical_url = get_permalink();
	}
        /** Echo out the canonical link to the header **/
	echo '';
	?>
	

Alternatively, you can add the code into your theme’s functions.php file if you don’t want to or can’t edit your header file.

In functions.php, add the following function:


function Insert_Canonical_In_Head() 
{
    global $post;
    if ( !is_singular()) //if it is not a post or a page
        return;
		/** Add Canonical Tag **/
        $current_term = '';
	$canonical_url = '';

	if ( is_front_page() && is_main_query() ) 
	{
        /** We're On The Home Page **/
		$canonical_url = site_url();
	}
	elseif (is_category()) 
	{
        /** We're On A Category Page **/
		$current_term = get_queried_object();

		if ($current_term) 
		{
		  $canonical_url = get_term_link( $current_term );
		}
	}
	else
	{
        /** We're on a Post or Page 88?
		 $canonical_url = get_permalink();
	}
        /** Echo out the canonical link to the header **/
	echo ''. PHP_EOL;
        echo "";
}

add_action( 'wp_head', 'Insert_Canonical_In_Head', 5 );

Disclaimer: The code on this website is provided "as is" and comes with no warranty. The author of this website does not accept any responsibility for issues arising from the use of code on this website. Before making any significant changes, ensure you take a backup of all files and do not work directly on a live/production website without thoughly testing your changes first.

Leave a Reply

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