Using WordPress ‘get_canonical_url’ PHP filter

The get_canonical_url WordPress PHP filter allows you to modify the canonical URL for a specific post.

Usage

add_filter('get_canonical_url', 'your_function_name', 10, 2);
function your_function_name($canonical_url, $post) {
    // your custom code here
    return $canonical_url;
}

Parameters

  • $canonical_url (string) – The post’s canonical URL.
  • $post (WP_Post) – Post object.

More information

See WordPress Developer Resources: get_canonical_url

Examples

Add a query string to the canonical URL

This code adds a custom query string to the canonical URL.

add_filter('get_canonical_url', 'add_query_string_to_canonical', 10, 2);
function add_query_string_to_canonical($canonical_url, $post) {
    $canonical_url = add_query_arg('ref', 'example', $canonical_url);
    return $canonical_url;
}

Change the canonical URL domain

This code changes the domain of the canonical URL to a new domain.

add_filter('get_canonical_url', 'change_canonical_domain', 10, 2);
function change_canonical_domain($canonical_url, $post) {
    $new_domain = 'https://www.new-domain.com';
    $parsed_url = wp_parse_url($canonical_url);
    $canonical_url = str_replace($parsed_url['host'], $new_domain, $canonical_url);
    return $canonical_url;
}

Remove the category from the canonical URL

This code removes the category from the canonical URL.

add_filter('get_canonical_url', 'remove_category_from_canonical', 10, 2);
function remove_category_from_canonical($canonical_url, $post) {
    $canonical_url = preg_replace('|/category/(.+?)/|', '/', $canonical_url);
    return $canonical_url;
}

Set the canonical URL to the home page for a specific post

This code sets the canonical URL to the home page for a specific post.

add_filter('get_canonical_url', 'set_canonical_to_home_page', 10, 2);
function set_canonical_to_home_page($canonical_url, $post) {
    if ($post->ID == 123) {
        $canonical_url = home_url();
    }
    return $canonical_url;
}

Disable the canonical URL for certain post types

This code disables the canonical URL for a specific post type.

add_filter('get_canonical_url', 'disable_canonical_for_post_type', 10, 2);
function disable_canonical_for_post_type($canonical_url, $post) {
    if ($post->post_type == 'custom_post_type') {
        $canonical_url = '';
    }
    return $canonical_url;
}