get_canonical_url
Allows you to change the canonical URL that WordPress outputs for posts.
Search engines use the canonical meta tag only when they detect duplicate content and do not have sufficient grounds to select a canonical address themselves. In all other cases, the canonical meta tag is ignored.
Usage
add_filter( 'get_canonical_url', 'wp_kama_get_canonical_url_filter', 10, 2 );
/**
* Function for `get_canonical_url` filter-hook.
*
* @param string $canonical_url The post's canonical URL.
* @param WP_Post $post Post object.
*
* @return string
*/
function wp_kama_get_canonical_url_filter( $canonical_url, $post ){
// filter...
return $canonical_url;
}
- $canonical_url(string)
- Canonical post URL.
- $post(WP_Post)
- Post object.
Examples
#1 Change a post's canonical URL
Suppose the post permalink rules were changed and a post_subpage query parameter was added. It contains a child page of the current post.
For example:
/my-post/ — the post URL.
/my-post/gallery/ — the URL of the post's static child page.
By default, the canonical meta tag for such custom pages is the same as for the post. However, these are separate pages with different content, so their canonical URLs should also differ.
Create the following hook to give these pages their own canonical URLs:
add_filter( 'get_canonical_url', 'subpages_canonical', 10, 2 );
function subpages_canonical( $canonical_url, $post ){
if( $subpage = get_query_var('post_subpage') ){
$canonical_url = user_trailingslashit( rtrim( get_permalink( $post ), '/' ) ."/$subpage" );
}
return $canonical_url;
}
#2 Change canonical URLs for home page pagination
Make every pagination URL on the home page canonicalize to the main page.
In other words, specify the home page https://example.com as canonical for URLs such as:
https://example.com/page/1 https://example.com/page/2 https://example.com/page/3
// Set the home page as canonical for every home pagination URL.
add_filter( 'get_canonical_url', 'wp_kama_get_canonical_url_filter', 10, 2 );
function wp_kama_get_canonical_url_filter( $canonical_url, $post ){
if( is_front_page() && is_paged() ){
return home_url();
}
return $canonical_url;
}
#3 Set a post's canonical URL from a custom field
Suppose there is a canonical_url post meta field where a custom canonical URL can be specified when needed. Add this code to make the field work:
// Change the post canonical URL if one is specified in post meta.
add_filter( 'get_canonical_url', 'wpkama_change_post_canonical_url', 10, 2 );
function wpkama_change_post_canonical_url( $canonical_url, $post ) {
$url = get_post_meta( $post->ID, 'canonical_url', true );
if ( $url ) {
$canonical_url = $url;
}
return $canonical_url;
}Changelog
| Since 4.6.0 | Introduced. |
Where the hook is called
return apply_filters( 'get_canonical_url', $canonical_url, $post );