How would I use
wpseo_canonical filter
to set a canonical URL for
the posts inwww.example.com/uk/
?E.g. the blog post
www.example.com/uk/blog/post-1/
should have a
canonical URL ofwww.example.com/blog/post-1/
I believe.
I don’t know if that should be the canonical URL, but if you are asking how can that be done, then this would do it, for the core post
post type:
function prefix_filter_canonical_example( $canonical ) {
if ( ! is_main_site() && is_single() ) {
// Get the ID of the main blog/site.
$main_site_id = get_main_site_id();
// Get the slug of the current post.
$post_slug = get_queried_object()->post_name;
// Switch to the main site and find a post with the same slug.
switch_to_blog( $main_site_id );
$posts = get_posts( array(
'post_type' => 'post',
'name' => $post_slug,
) );
// If found, then use its permalink as the canonical URL.
$permalink = empty( $posts ) ? '' : get_permalink( $posts[0] );
restore_current_blog();
return $permalink ? $permalink : $canonical;
}
return $canonical;
}
add_filter( 'wpseo_canonical', 'prefix_filter_canonical_example' );
Or if all the sites use the same permalink structure, e.g. %postname%
, and that the same post also exists in the main site (i.e. same slug and post type), then you could simply use the current post’s permalink and just replace the WordPress “home” URL in that permalink.. E.g.
function prefix_filter_canonical_example( $canonical ) {
if ( ! is_main_site() && is_single() ) {
// Get the ID of the main blog/site.
$main_site_id = get_main_site_id();
// Get the data of the main and current sites.
$main_blog = get_blog_details( $main_site_id );
$current_blog = get_blog_details();
// Replace the home URL in the current post's permalink.
return str_replace( "$current_blog->home/", "$main_blog->home/", get_permalink() );
}
return $canonical;
}
add_filter( 'wpseo_canonical', 'prefix_filter_canonical_example' );
So I hope that helps, but remember that switch_to_blog()
does not switch plugins, and thus get_permalink()
might not return the “correct” permalink that would otherwise be returned if plugins were also switched.
Also, a hook can run in various places on the same page, so you might want to cache the result of the $permalink
value in the 1st snippet above..