Simple Canonical Redirect for WooCommerce

If your Woocommerce products are within multiple categories or hierarchies they will have multiple potential URLS. I always find this annoying. If you also find it odd that the URL displayed in the post edit screen under the Title box, which is named “permalink” is not automatically the go-to URL you might wish to utilise the following code to fix this with a 301 redirect.

Example:

 

website.com/scotland/glenelg-skye-ferry

would now redirect to the (correct) Permalink url:

website.com/travel/scotland/glenelg-skye-ferry

The code:

add_action('template_redirect', 'redirect_to_canonical_url');
function redirect_to_canonical_url() {
if (is_singular('product')) {
global $post;

// Get the canonical URL for the current product
$canonical_url = get_permalink($post->ID);

// Get the current URL
$current_url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

// Normalize URLs to avoid issues with trailing slashes, query strings, etc.
$canonical_url = trailingslashit($canonical_url);
$current_url = trailingslashit(preg_replace('/\?.*/', '', $current_url)); // Strip query string

// Compare and redirect if necessary
if ($current_url !== $canonical_url) {
wp_redirect($canonical_url, 301);
exit;
}
}
}

Leave a Reply