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
- Detect Product Pages: The code checks if the page is a product using
is_singular('product')
. - Generate New URL: It constructs the desired URL with the
/product/
prefix. - 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.