TOPIC: PERMALINK
Add Canonical Tags to WordPress without plugins
31st March 2025Search engines need to know which is which because they cannot know which is the real content when there is any duplication, unless you tell them. That is where canonical tags come in handy. By default, WordPress appears to add these for posts and pages, which makes sense. However, you can add them for other places too. While a plugin can do this for you, adding some code to your theme's functions.php file also does the job. This is how it could look:
function add_canonical_link() {
global $post;
// Check if we're on a single post/page
if (is_singular()) {
$canonical_url = get_permalink($post->ID);
}
// For the homepage
elseif (is_home() || is_front_page()) {
$canonical_url = home_url('/');
}
// For category archives
elseif (is_category()) {
$canonical_url = get_category_link(get_query_var('cat'));
}
// For tag archives
elseif (is_tag()) {
$canonical_url = get_tag_link(get_query_var('tag_id'));
}
// For other archive pages
elseif (is_archive()) {
$canonical_url = get_permalink();
}
// Fallback for other pages
else {
$canonical_url = get_permalink();
}
// Output the canonical link
echo '' . "\n";
}
// Hook the function to wp_head
add_action('wp_head', 'add_canonical_link');
// Remove default canonical link
remove_action('wp_head', 'rel_canonical');
The first part defines a function to define the canonical URL and create the tag to be added. With that completed, the penultimate piece of code hooks it into the wp_head
part of the web page, while the last function gets rid of the default link to get avoid any duplication of output.
Post titles on Technorati
28th January 2007I have had a look at how the posts from this blog are listed on Technorati and most if not all the titles are coming through as "Permalink". I was going to try WordPress.com support, but they are off for the weekend. A trip to the WordPress.com forums was then in order and a few helpful folk put me right on this one: apparently Technorati uses the permalink titles when extracting post summaries from WordPress.com blogs and in the Andreas04 theme that I am using, these are all hard-coded as "Permalink". I have left the theme's author in on this and going to try WordPress.com feedback tomorrow. In technical terms and from what I can see, the fix needed is as follows: change title="Permalink"
totitle="Permanent Link: "
in the single.php, page.php and index.php files in the theme.