Canonicalize your WordPress

WordPress recently updated it’s core library to handle Canonicalization of pages and posts to avoid duplicate content(as explained here).

Here is a small snippet of code to provide you with a more flexible and customizable way of making canonical URLs for your site.

function seo_canonical() {
	global $post;
	// We remove WP's canonical function first
	remove_action('wp_head', 'rel_canonical');

	// Do the canonicals
		$canonical = get_bloginfo('url');
		if (is_single() || is_page()) {
			$canonical = get_permalink($post->ID);
		} else if (is_day()) {
			$year = get_query_var('year');
			$month = get_query_var('year');
			$day = get_query_var('day');
			$canonical = get_year_link($year, $month, $day);
		} else if (is_month()) {
			$year = get_query_var('year');
			$month = get_query_var('monthnum');
			$canonical = get_year_link($year, $month);
		} else if (is_year()) {
			$year = get_query_var('year');
			$canonical = get_year_link($year);
		} else if (is_author()) {
			$author = get_query_var('author');
			$canonical = get_author_posts_url($author);
		} else if (is_category()) {
			$cat = get_query_var('cat');
			$canonical = get_category_link($cat);
		} else if (is_tag()) {
			$tag = get_query_var('tag_id');
			$canonical = get_tag_link($tag);
		}
		echo '';
}

add_action('wp_head', 'seo_canonical');

this method will serve well to those who are really into customizing their SEO.

This entry was posted in Tutorials and tagged , , , . Bookmark the permalink.

Leave a Reply

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