How to Add Canonical Tag to Post Copies

Whether you’re already using or just going to use my “Simple Multisite Crossposting” plugin, you may be wondering, if there is any way to prevent the content duplicates?

Of course it is! You can easily prevent content duplicates with <link rel="canonical"> tag.

In case you’re not using any SEO plugins, then you can easily implement it with a simple code snippet from below. Read also how to insert it to the website. If you’re super-uncomfortable with code snippet, there is an add-on as well.

add_filter( 'get_canonical_url', function( $canonical_url, $post ) {
	
	// PLEASE SPECIFY HERE THE MAIN BLOG ID (how to find it out below)
	$main_blog_id = 1;

	if( ! is_multisite() || $main_blog_id == get_current_blog_id() || ! ( $data = get_post_meta( $post->ID, '_crosspost_to_data', true ) ) || ! is_array( $data ) || ! array_key_exists( $main_blog_id, $data ) ){
		return $canonical_url;
	}

	switch_to_blog( $main_blog_id );
	$permalink = get_permalink( $data[ $main_blog_id ] );
	restore_current_blog();

	return $permalink ? $permalink : $canonical_url;

}, 9999, 2 );

You can insert this code “as is” to the specific website where you would like a canonical tag to be displayed. The only thing you have to specify in this code is the ID of the main blog which URLs you would like to be displayed in rel=canonical tags.

How to find out blog ID? Easy enough. In your Network Admin please go to Sites page and then click “Edit” link near the site you need. Then please look at the page URL:

how to get multisite network site ID
We can see here that site ID is 2.

So you can replace the only line in the code above like this:

$main_blog_id = 2;

Add-on

You can download an add-on for canonical URLs as well. It is free.

You might need this add-on in two cases:

  1. You do not know or do not want to use code snippet as a solution.
  2. You don’t have a “main website” and would like to add <link rel="canonical"> tag to post copies, regardless of the website where the original post is created.

Need more help?