rel_canonical()WP 2.9.0

Outputs the tag <link rel=canonical> to the screen. Automatically called during the wp_head action to output the canonical link in the document's head.

Works only for posts of type is_singular().

To disable the canonical link in the head section, you need to remove the hook:

remove_action( 'wp_head', 'rel_canonical' );

The meta tag canonical is used by search engines only in one case: when the search engine has discovered duplicate content, and it does not have sufficient grounds to choose a canonical address.

In all other cases, the canonical is ignored. That is, specifying a canonical on pagination pages to any other page except itself makes no sense, as the pagination page is not duplicate content. Except, of course, in cases where it actually has the same content. However, I can't imagine how this could be done in a sane mind.

© Demi Murych

No Hooks.

Returns

null. Outputs the html tag <link rel='canonical' href='$link' />

Usage

rel_canonical();

Examples

0

#1 Display the canonical link in the head part

Add the following code to header.php in the <head> part of the document, so that all is_single() pages will have a canonical link:

<?php rel_canonical(); ?>

// output: <link rel='canonical' href='$link' />\n
0

#2 Removing canonical links on comment pagination pages

On comment pagination pages, the canonical URL looks like this: example.com/about/comment-page-1/. This is not always good, it seems because the content of the posts in this case is duplicated.

To fix this we use the following code:

add_filter( 'get_canonical_url', 'remove_comment_page_canonical_url', 10, 2 );

function remove_comment_page_canonical_url( $canonical_url, $post ){

	// for comment page of current post only
	if ( get_query_var( 'cpage', 0 ) && $post->ID === get_queried_object_id() ) {
		$canonical_url = get_permalink( $post );
	}

	return $canonical_url;
}

The details of this code I answered in the question.

Changelog

Since 2.9.0 Introduced.
Since 4.6.0 Adjusted to use wp_get_canonical_url().

rel_canonical() code WP 6.8.3

function rel_canonical() {
	if ( ! is_singular() ) {
		return;
	}

	$id = get_queried_object_id();

	if ( 0 === $id ) {
		return;
	}

	$url = wp_get_canonical_url( $id );

	if ( ! empty( $url ) ) {
		echo '<link rel="canonical" href="' . esc_url( $url ) . '" />' . "\n";
	}
}