0
0
WordpressHow-ToBeginner · 3 min read

How to Set Canonical URL in WordPress Easily

In WordPress, you can set a canonical URL by adding a rel="canonical" link tag in the <head> section of your pages. This can be done manually in your theme's header.php file or automatically using SEO plugins like Yoast SEO that handle canonical URLs for you.
📐

Syntax

The canonical URL is set using a <link> tag with the attribute rel="canonical" inside the HTML <head> section. It looks like this:

  • rel="canonical": tells search engines this is the preferred URL.
  • href="URL": the full URL you want to set as canonical.
html
<link rel="canonical" href="https://example.com/preferred-page/" />
Output
No visible output; search engines read this tag to understand the preferred URL.
💻

Example

This example shows how to add a canonical URL manually in a WordPress theme by editing the header.php file. It uses WordPress functions to get the current page URL dynamically.

php
<?php
function add_canonical_url() {
    if (is_singular()) { // Check if it's a single post/page
        $canonical_url = get_permalink();
        echo '<link rel="canonical" href="' . esc_url($canonical_url) . '" />\n';
    }
}
add_action('wp_head', 'add_canonical_url');
?>
Output
<link rel="canonical" href="https://example.com/current-post-or-page/" />
⚠️

Common Pitfalls

Common mistakes when setting canonical URLs in WordPress include:

  • Setting incorrect or relative URLs instead of full absolute URLs.
  • Adding multiple canonical tags on the same page, which confuses search engines.
  • Not using WordPress functions to get URLs, causing broken or wrong links.
  • Relying on manual edits without testing if the canonical tag appears correctly.

Using SEO plugins like Yoast SEO is recommended to avoid these issues, as they automatically manage canonical URLs.

php
<?php
// Wrong way: hardcoding relative URL
echo '<link rel="canonical" href="/my-post/" />';

// Right way: use WordPress function for full URL
echo '<link rel="canonical" href="' . esc_url(get_permalink()) . '" />';
📊

Quick Reference

Summary tips for setting canonical URLs in WordPress:

  • Always use full absolute URLs starting with https://.
  • Use WordPress functions like get_permalink() to get the current page URL.
  • Add the canonical tag inside the <head> section using the wp_head hook.
  • Consider SEO plugins like Yoast SEO or Rank Math to automate canonical URL management.
  • Test your pages with browser DevTools to confirm the canonical tag is present and correct.

Key Takeaways

Set canonical URLs in WordPress using a tag in the section.
Use WordPress functions like get_permalink() to get the correct full URL dynamically.
Avoid multiple or incorrect canonical tags to prevent SEO issues.
SEO plugins like Yoast SEO can manage canonical URLs automatically and safely.
Always verify the canonical tag appears correctly using browser DevTools.