Canonical URLs play a crucial role in SEO (Search Engine Optimization) by helping search engines understand the preferred version of a web page when multiple URLs point to the same content. This is particularly important for avoiding duplicate content issues, which can negatively impact a website’s search engine rankings.
Why are Canonical URLs Important?
Avoid Duplicate Content Issues: Search engines may see different URLs with the same content as duplicate content, which can dilute the SEO value of your pages. Canonical URLs help consolidate ranking signals for the preferred version of the content.
Consolidate Ranking Signals: When there are multiple versions of a page (e.g., HTTP and HTTPS, www and non-www), using canonical tags can consolidate the ranking signals to the preferred version, helping to improve the page’s SEO performance.
Improve Crawl Efficiency: By specifying the canonical URL, you help search engines understand which version of the page to crawl and index, reducing crawl inefficiencies.
You can implement canonical URLs using the <link rel=”canonical” href=”https://www.example.com/original-page/” /> tag in the HTML <head> section of your web pages. Replace https://www.example.com/original-page/ with the URL of the preferred version of your content.
For example:
<head>
<link rel=”canonical” href=”https://www.example.com/original-page/” />
</head>
Yoast SEO Canonical URLs – API documentation
To change the canonical URL that Yoast SEO generated for a URL programmatically, you can use the wpseo_canonical filter.
Change the canonical URL
For example, the following code would change the canonical on a page with ID 12345:
/**
* Filters the canonical URL.
*
* @param string $canonical The current page’s generated canonical URL.
*
* @return string The filtered canonical URL.
*/
function prefix_filter_canonical_example( $canonical ) {
if ( is_page( 12345 ) ) {
$canonical = ‘https://example.com/canonical-url/’;
}
return $canonical;
}
add_filter( ‘wpseo_canonical’, ‘prefix_filter_canonical_example’ );
Remove the canonical URL
If you want to completely remove the canonical URL from a page, simply return false for that page, like so:
/**
* Filter the canonical URL.
*
* @param string $canonical The current page’s generated canonical URL.
*
* @return bool|string The filtered canonical URL or false when we want to remove it.
*/
function prefix_filter_canonical_example( $canonical ) {
if ( is_page( 12345 ) ) {
return false;
}
return $canonical;
}
add_filter( ‘wpseo_canonical’, ‘prefix_filter_canonical_example’ );
Or to remove it from all pages, simply do:
add_filter( ‘wpseo_canonical’, ‘__return_false’ );
https://developer.yoast.com/features/seo-tags/canonical-urls/api/