How-To and Troubleshooting Canonical Links for Paginated Comments

admin2025-06-03  4

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:

<link rel='canonical' href='/' />

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='' />

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.

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:

<link rel='canonical' href='http://mysite/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/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.

Share Improve this question edited Mar 14, 2014 at 21:58 Rarst 100k10 gold badges161 silver badges298 bronze badges asked Mar 14, 2014 at 20:55 user15196user15196 311 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

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 );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748916272a314788.html

最新回复(0)