How to Add rel=canonical to WordPress Pages for Better SEO
Explanation
Adding a rel=canonical tag to your WordPress pages and posts helps search engines understand which URL is the preferred version when you have similar or duplicate content. This can improve your site's SEO by preventing duplicate content issues.
Here's a simple way to add a canonical tag:
- The function checks if you're viewing a single post or page using
is_singular()
. - It then grabs the URL of the current post or page with
get_permalink()
. - Finally, it outputs the canonical link tag in the
<head>
section of your site.
If you're using Yoast SEO, it might already add its own canonical tags. To avoid duplicates, the code checks if Yoast is active and removes its canonical tag using remove_action()
.
This setup ensures you have a single, clean canonical tag on each page, which is great for SEO and keeps search engines happy!
Code
<?php
// Add rel=canonical to WordPress pages and posts
function wp_dudecom_add_canonical_tag() {
if (is_singular()) {
global $post;
// Get the canonical URL
$canonical_url = get_permalink($post->ID);
// Output the canonical link tag
echo '<link rel="canonical" href="' . esc_url($canonical_url) . '" />' . "\n";
}
}
add_action('wp_head', 'wp_dudecom_add_canonical_tag');
// Remove duplicate canonical tags if Yoast SEO is active
function wp_dudecom_remove_yoast_canonical() {
if (defined('WPSEO_VERSION')) {
remove_action('wpseo_head', array(WPSEO_Frontend::get_instance(), 'canonical'), 10);
}
}
add_action('wp', 'wp_dudecom_remove_yoast_canonical');
?>
Instructions
File Location: Add the following code to your theme's functions.php
file or a custom plugin file.
Prerequisites:
- Access to your WordPress theme files or the ability to create/edit a plugin.
- Basic understanding of how to edit PHP files.
- Optional: Yoast SEO plugin installed (if applicable).
Implementation Steps:
- Access your WordPress Dashboard: Log in to your WordPress admin panel.
- Navigate to Appearance > Theme Editor: If editing
functions.php
, or Plugins > Add New > Create a new plugin if you prefer using a plugin file. - Locate the
functions.php
file: In the Theme Editor, find thefunctions.php
file in the right-hand sidebar under "Theme Files". - Copy and Paste the Code: Insert the provided code snippet at the end of the
functions.php
file or in your custom plugin file. - Save Changes: Click the "Update File" button to save your changes.
- Verify Implementation: Visit a single post or page on your site and view the page source to ensure the
rel=canonical
tag is present in the<head>
section. - Check for Yoast SEO: If you have Yoast SEO installed, ensure that the duplicate canonical tag is removed by checking the page source for only one
rel=canonical
tag.
If you need help with implementation or require more advanced functionality, consider using the services of wp-dude.com.