rel_canonical()WP 2.9.0

Outputs rel=canonical for singular queries.

No Hooks.

Return

null. Nothing (null).

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.4.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";
	}
}