Canonicalize your WordPress

By Steven Chang

January 24, 2011


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.

Steven Chang

About the author

The roles I play: Leader, Husband, Dad, Son, Brother, Friend, Programmer, Investor, Trader, Marketer, Student, Teacher, Influencer.

  • thanks…
    nice one, but, how to canonicalize paged in index and archive?

    and i have alot trouble to create canonical and different title for paged page. (when separate a page in paged format, it have the same title with different url.)
    >>no seo plugin have this feature (yet)

    sorry for my engish, its not my native language

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

    Direct Your Visitors to a Clear Action at the Bottom of the Page

    >