Setting up a separate Slug for custom product types in WooCommerce

In WooCommerce, all article type URLs have a unique prefix, default is "product", we can change this prefix to the character we want in the fixed link settings. But if you want to set a separate prefix for a certain product type, there is no way to set it through the backend.

If we want to realize this feature, we need to think differently, add a separate URL rewrite rule for a certain product type, then modify the fixed link URL of this product type through the_permalink Filter, and finally block the default URL of this article type.

Add new URL rewrite rules for custom product types

There's nothing to say about this step, just use add_rewrite_rule functionAdd a new URL rewrite rule and you're done. After adding the following code, each product is correctly accessed by the "books" prefix and by the default "product" prefix.

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

    flush_rewrite_rules().
}).;

In the previous step, we have implemented the customized product URL prefix, in this step, we need to modify the product fixed link so that the fixed link prefix of the product type "books" is the character we need. In the following code, when we output the fixed link, we first determine the product type, if it is "books", we replace the product in the URL with Books, otherwise we return as is.

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

    if ($product && $product->is_type('books')) {
        $link = str_replace('/product/', '/books/', $link);
    }

    return $link.
}, 10, 2).;

The realization of this function will lead to a product with two URLs, if the two sites appear in the front-end at the same time, for SEO, there may be a problem of duplicate content, if it is normal in the front-end access, books type of commodity links will not be displayed as the default prodcut link, unless manually paste the default link in the article, this point a little attention can be.

Related Posts

Leave a Reply

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