How to Filter Canonical URLs in WordPress

The canonical URL can be modified programmatically in WordPress using the get_canonical_url filter hook.

Recently I was working on a site that needed custom canonical URLs on specific search result pages. I went looking for the documentation on filtering the canonical URLs, but while the existence of the filter is documented, I could not find the documentation for using the filter. Here’s what I came up with:

function edit_canonical_urls( $canonical_url ) {
	if ( !empty( intval( $_GET['entry-number'] ) ) ) {
		global $wp;
		$new_canonical_url = home_url( add_query_arg( array(), $wp->request ) ) . '/?entry-number=' . intval( $_GET['entry-number'] );
		return $new_canonical_url;
	}

	return $canonical_url;
}
add_filter( 'get_canonical_url', 'edit_canonical_urls' );

Our function accepts one argument, which holds the default permalink for the page. Next we check if there is a value for “entry-number” in the query string for this page (“entry-number” is the custom query parameter I’m using for this example). If there is, we return the new canonical URL, but if not, we simply return the original canonical URL.

Posted in

2 thoughts on “How to Filter Canonical URLs in WordPress”

    1. Hi Nigel!

      If you’re trying to get the canonical URL, then ‘wp_get_canonical_url’ is the function you want to call. If you want to change the canonical URL, ‘get_canonical_url’ is the filter you can use to do that.

      The ‘get_canonical_url’ filter is applied to the return value of the ‘wp_get_canonical_url’ function in the /wp-includes/link-template.php file. If you don’t feel like digging through the WordPress source code, here’s a link to the changeset where it was added: https://core.trac.wordpress.org/changeset/37685

Leave a Reply to alexmansfield Cancel Reply

Your email address will not be published. Required fields are marked *