Environment: Wordpress page, with Yoast SEO plugin installed (and indexing enabled)
In the child theme root directory:
- Add the following code to the
functions.php
file:
function mackan_fix_canonical_links_js() {
wp_enqueue_script('custom', get_stylesheet_directory_uri().'/fix-canonical-links.js', array(), false, true);
}
add_action('wp_enqueue_scripts', 'mackan_fix_canonical_links_js');
- Create a
fix-canonical-links.js
file with the following content inside:
// update canonical links
const canonicalLinks = document.querySelectorAll("link[rel='canonical']");
if (canonicalLinks.length) {
canonicalLinks.forEach((link) => {
link.href = location.href
})
} else {
const linkElement = document.createElement('link');
linkElement.setAttribute('rel', 'canonical');
linkElement.setAttribute('href', location.href);
document.head.appendChild(linkElement);
}
// update OG:URL property (if exisits)
const metaOgUrls = document.querySelectorAll("meta[property='og:url']");
metaOgUrls.forEach((ogUrl) => {
ogUrl.content = location.href
});