Custom WooCommerce Product URL Redirect for Better URL Structure

In a recent Business Bloomer Club Slack thread, a WooCommerce user shared a challenge with their product URL structure. The site currently uses URLs in the format website.com/product-name, but they wanted to revert to WooCommerce’s default URL format: website.com/product/product-name.

With over 900 products, manually creating redirects would be overwhelming, and they needed a solution that wouldn’t impact performance or SEO. The user also wanted to know if a snippet or .htaccess method could handle this redirect, while keeping the process efficient and clean.

To make this transition easier, a PHP snippet in WordPress can help handle the redirects automatically, avoiding .htaccess changes. Here’s how you can set it up so that product pages will redirect to the new URL structure with minimal hassle.

Setting Up the WooCommerce Product URL Redirect

Here’s a PHP snippet you can add to your theme’s functions.php file. It checks if the current URL belongs to a product page, then appends the /product/ prefix to create a 301 redirect to the updated URL. This solution works well with SEO plugins like Rank Math and keeps the changes seamless for visitors.

function custom_redirect_to_specific_product_page() {
    if (is_singular('product')) {
        global $post;
        $product_slug = $post->post_name;
        $redirect_url = home_url('/product/' . $product_slug);
        wp_redirect($redirect_url, 301);
        exit;
    }
}
add_action('template_redirect', 'custom_redirect_to_specific_product_page');

How It Works

  1. Detect Product Pages: The code checks if the page is a product using is_singular('product').
  2. Generate New URL: It constructs the desired URL with the /product/ prefix.
  3. 301 Redirect for SEO: The wp_redirect function uses a 301 status, so search engines recognize the change as permanent, preserving any existing SEO benefits.

This method is simple and efficient, applying the redirect automatically for all products without the need to manually set each one. It’s a clean way to adjust URL structure, keeping the site easy to manage without sacrificing performance.

Related content

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

Reply

Your email address will not be published. Required fields are marked *