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

Leave a Comment

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