How to Set a Custom URL Slug for Specific WooCommerce Product Types

By default, all WooCommerce products share a universal URL prefix, which is typically set to /product/. While you can easily change this globally in the WordPress Permalink settings, WooCommerce doesn’t provide a built-in way to assign unique slugs to specific product types (e.g., using /books/ for a “Book” product type while keeping /product/ for others).

To achieve this granular control over your URL structure, we need to implement custom rewrite rules and use the the_permalink filter to dynamically update the product links. This approach allows you to create a more intuitive and SEO-friendly site structure.

1. Adding Custom Rewrite Rules

The first step is to tell WordPress how to handle the new URL structure. We use the add_rewrite_rule function to map our custom prefix (e.g., books) to the standard WooCommerce product query. After adding this code, products will be accessible via both the custom and the default prefixes.

 add_action('init', function ()
{
    add_rewrite_rule(
        '^books/([^/]*)/?',
        'index.php?product=$matches[1]',
        'top'
    );

    // Note: In a production environment, you should flush rules only once
    // flush_rewrite_rules();
});

Now that WordPress knows how to resolve the new URLs, we need to ensure that the site actually uses them. By hooking into the the_permalink filter, we can check the product type and replace the default /product/ string with our custom /books/ slug whenever a link is generated for that specific type.

add_filter('the_permalink', function ($link, $post)
{
    global $product;

    // Check if the current post is a product and matches our custom type
    if ($product && $product->is_type('books')) {
        $link = str_replace('/product/', '/books/', $link);
    }

    return $link;
}, 10, 2);

Implementing this feature results in two valid URLs for the same product. To avoid potential SEO issues with duplicate content, ensure that your canonical tags are correctly set (which most SEO plugins handle automatically). By using this method, your “books” product type will consistently display with the custom slug in menus, search results, and shop loops, providing a cleaner experience for both users and search engines.

Related Posts

Leave a Reply

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