Issue description
A Client has a website on WordPress, they use Yoast SEO plugin.
By default Yoast generated wrong canonical tags for Blog pagination pages :
for example:
a page https://website.com/blog/page/2/ had a canonical tag https://website.com/blog/page/2
and they had a redirection from https://website.com/blog/page/2 to https://website.com/blog/page/2/
So – there is quite an issue here!
Solution
As a solution – necessary to add a trailing slash at the end of canonical tags for pagination pages. A second variant – is to remove the canonical tags for pagination pages at all.
(The difference between these two – is canonical tags can handle URLs with attributes like ?gclid= )
Code
As a solution – necessary to insert a piece of code in functions.php:
Appearance – Theme File Editor – functions.php
Variant 1: To add trailing slash for paginated pages
<?php
/**
* Forces a trailing slash on Yoast SEO canonical URLs for paginated pages.
*
* @param string $canonical The canonical URL.
* @return string The modified canonical URL.
*/
function force_trailing_slash_on_yoast_pagination_canonical( $canonical ) {
// Check if it's a paginated page (e.g., /page/2/)
if ( is_paged() ) {
// Use trailingslashit() to ensure a trailing slash is present
return trailingslashit( $canonical );
}
return $canonical;
}
add_filter( 'wpseo_canonical', 'force_trailing_slash_on_yoast_pagination_canonical', 10 );
?>
Variant 2: To remove canonicals from paginated pages
<?php
/**
* Remove Yoast SEO's canonical tag from paginated pages.
*
* @param string $canonical The canonical URL.
* @return string|false The modified canonical URL or false to remove it.
*/
function remove_yoast_canonical_from_pagination( $canonical ) {
if ( is_paged() ) {
return false; // Return false to remove the canonical tag
}
return $canonical;
}
add_filter( 'wpseo_canonical', 'remove_yoast_canonical_from_pagination', 10 );
?>