November 27th, 2009

Canonical URLs (Code Snippet – WordPress)

While developing websites, most probably you would have heard about specifying canonical URLs or come across an article on it.

For the benefit of those who haven’t, URL Canonicalization, also known as URL normalization is a process by which URLs are modified and standardized in a consistent manner. Search engines (Google, Yahoo, Bing) allows site owners to specify their preferred version of a page through the canonical meta tag. This is useful in the event that there are multiple URLs pointing to the same page/content.

Adding support for canonical URL meta tag is normally one of the first things I do in recent months. The following is the code I usually use for my WordPress themes:

function post_canonical_url() {
   if ( is_singular() ) {
     $canonical_url = '<link rel="canonical" href="' . get_permalink() . '"/>';
   } elseif ( is_home() ){
     $canonical_url = '<link rel="canonical" href="' . get_bloginfo('home') . '"/>';
   }
echo $canonical_url;
}
add_action('wp_head', 'post_canonical_url')
?>

For WordPress, it is easy to achieve through a plugin. However, for those who don’t want to add another plugin, or want a simple, no-frills method, just copy the above code into your functions.php.

After adding the above code,  a canonical meta tag will be added to your index, posts and pages.

(EDIT 291109: This code is only needed in WordPress 2.8 and below. According to the development builds of WordPress 2.9, it has native support for canonical URLs).

Shortlinks

Leave a Comment

Or Comment using....

Facebook Connect

Skip the hassle of typing in the required fields! Link Fusedthought Studio with your Google, Facebook or other connect enabled accounts.

Top