So I'm trying to remove the canonical link in the header of WordPress for paginated pages but all the suggestions I tried aren't working.
Here is my code which is in my functions.php file:
function my_add_noindex_tags(){
$paged = intval( get_query_var( 'paged' ) );
if(is_search() || is_404() ) :
echo '<meta name="robots" content="noindex,follow">';
endif;
if ($paged >= 2) :
add_filter( 'wpseo_canonical', '__return_false', 10, 1 );
remove_action('wp_head', 'rel_canonical');
echo '<meta name="robots" content="noindex,follow">';
endif;
}
add_action('wp_head','my_add_noindex_tags', 4 );
I know the code inside if ($paged >= 2) :
runs because this tag <meta name="robots" content="noindex,follow">
is in the head section.
Anyone know where I might be going wrong.
The issue here is the canonical link added by Yoast SEO aren't properly removed as expected.
Cheers
After going through the Yoast SEO codes, it seems like the canonical action is added to wpseo_head
action.
You either have to use priority 1 when adding your function to run in wp_head
to get this to execute properly, or do it with the appropriate method below ie. using wpseo_head
action.
function remove_canonical() {
$paged = intval( get_query_var( 'paged' ) );
if ($paged >= 2) {
add_filter( 'wpseo_canonical', '__return_false', 10 );
}
}
add_action( 'wpseo_head', 'remove_canonical', 4);