Canonical URLs on Archive Pages
Adds canonical link tags to the blog page, category, tag, author and post type archives, which WordPress only does for single posts and pages by default.
Opens WPIDE on
Code
add_action( 'wp_head', function () {
if ( is_singular() || is_404() || is_search() || defined( 'WPSEO_VERSION' ) || defined( 'RANK_MATH_VERSION' ) || defined( 'AIOSEO_VERSION' ) || defined( 'SEOPRESS_VERSION' ) || defined( 'THE_SEO_FRAMEWORK_VERSION' ) ) {
return;
}
$url = '';
if ( is_front_page() ) {
$url = home_url( '/' );
} elseif ( is_home() ) {
$url = get_permalink( (int) get_option( 'page_for_posts' ) );
} elseif ( is_category() || is_tag() || is_tax() ) {
$url = get_term_link( get_queried_object() );
} elseif ( is_author() ) {
$url = get_author_posts_url( get_queried_object_id() );
} elseif ( is_post_type_archive() ) {
$type = get_query_var( 'post_type' );
$url = get_post_type_archive_link( is_array( $type ) ? reset( $type ) : $type );
}
if ( ! $url || is_wp_error( $url ) ) {
return;
}
$paged = (int) get_query_var( 'paged' );
if ( $paged > 1 ) {
global $wp_rewrite;
$url = $wp_rewrite->using_permalinks() ? user_trailingslashit( trailingslashit( $url ) . $wp_rewrite->pagination_base . '/' . $paged, 'paged' ) : add_query_arg( 'paged', $paged, $url );
}
echo '<link rel="canonical" href="' . esc_url( $url ) . '" />' . "\n";
}, 1 );
Notes
Each paginated page points to itself. Skipped when a major SEO plugin is active.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.