There’s a great plugin called Yoast SEO by Yoast available in the WordPress repository. It includes a wide range of features that meet the needs of most beginner — and even advanced — SEO specialists.
However, this post is not about its feature set or advantages over other similar plugins. Instead, we’ll focus on pagination in canonical URLs for tags and categories.
So, what are canonical URLs and why are they important? Google’s documentation explains it as follows:
A canonical URL is the URL of the page that Google considers the “master” version among several duplicates on your site. For example, if the same page is accessible at example.com?dress=1234 and example.com/dresses/1234, one of them will be chosen as the canonical version. Note that the pages don’t have to be exact copies and can be on different domains.
This applies not only to Google, but also to Yandex and other search engines.
Now let’s get back to the Yoast plugin. By default, paginated tag and category URLs look like this:
<link rel="canonical" href="http://wordpress.l/category/bez-rubriki/page/2/" /> <link rel="canonical" href="http://wordpress.l/tag/teg1/page/2/" />
Which isn’t great from an SEO perspective. It’s better when they link to the main page of the category or tag (or any custom taxonomy, if you use them on your site). In that case, they should look like:
<link rel="canonical" href="http://wordpress.l/category/bez-rubriki/page/" /> <link rel="canonical" href="http://wordpress.l/tag/teg1/page/" />
To implement this behavior, we’ll refer to the Yoast plugin documentation. It frequently mentions the wpseo_canonical filter. Let’s try using it to improve the situation. Here’s the code:
add_filter('wpseo_canonical', function($canonical) {
if(is_category() && is_paged())
{
$Term = get_term_by('id', get_query_var('cat'), 'category');
return get_category_link($Term -> term_id);
}
elseif(is_tag() && is_paged())
{
$Term = get_term_by('slug', get_query_var('tag'), 'post_tag');
return get_tag_link($Term -> term_id);
}
return $canonical;
}, 10, 1);What this code does:
- Checks whether we are on a category or tag page and whether it’s a paginated page (2nd, 3rd, etc.).
- Retrieves term data using the
get_term_by()WordPress function. - Generates a link to the main page of the term — using
get_category_link()for categories andget_tag_link()for tags. - For all other pages, it returns the default canonical URL generated by the plugin.
