Written on 17. August 2022 by Lennart Christensen

Change Canonical URL with wp_head

The canonical url is an important part of SEO. If you do not set the canonical url correctly, search engines may not index the content correctly or worse, index the wrong page and you will lose traffic due to duplicate pages.

Solution: with the wp_head filter you can change the canonical url for any post, page or other post type on your WordPress website. This ensures that your pages are indexed correctly and that you don't lose traffic due to duplicate pages.

In this example, a canonical tag is set for the post type "bil" and on the posts that have an input in the field "img_parent". The canonical url for these items is then set to point to its parent, which in this case is retrieved via the input field "img_parent":

function canonical_url( {
	if(!is_singular('bil') ) { return false; }
	if(!get_field('img_parent')) { return false; }
	$parenturl = get_the_permalink(get_field('img_parent'));
	echo '';
}
add_filter( 'wp_head', 'canonical_url', 10, 2 );

If you want to change it for a specific post or post type, just replace "bil" with that post type. For example, if you want to change the canonical url for a "product", use "product" instead of "bil", as shown in my example.