How-To and Troubleshooting Canonical Links for Paginated Comments

It seems that when you paginate comments, the additional pages don’t have their canonical links point back to the original page. This would seem to lead to duplicate content issues (i.e. same post, just different comments on p.2, p.3, etc.).

For example, on the first page of the post, the canonical link looks like this:

Read More
<link rel='canonical' href='http://mysite.com/uncategorized/my-post/' />

When I paginate the comments, however, I now have multiple pages. I would like all of those pages to point back to the original page. Instead, they look like this:

<link rel='canonical' href='http://mysite.com/uncategorized/my-post/comment-page-2/#comments' />

I did find some code I thought might do the trick, but it didn’t. (Maybe it’s old.)

Here’s the code I found:

function canonical_for_comments() {
global $cpage, $post;
if ( $cpage > 1 ) :
echo "n";
echo "<link rel='canonical' href='";
echo get_permalink( $post->ID );
echo "' />n";
endif;
}
add_action( 'wp_head', 'canonical_for_comments' );

Any ideas for how to change this so that all the canonical URLs point back to the original?

Thanks.

Related posts

Leave a Reply

1 comment

  1. Try specifying the priority for your function. You will also want to remove the default canonical link before adding your modified one. This worked on my site:

    function canonical_for_comments()
    {
        global $cpage, $post;
        if (!empty($cpage) && $cpage > 0) {
        remove_action('wp_head', 'rel_canonical');
        echo '<link rel="canonical" href="' . esc_url(get_permalink($post->ID)) . '" />';
        echo "n";
        }
    }
    add_action( 'wp_head', 'canonical_for_comments', 9 );