I know here is an information about the issue, but I didn't find full working solution.

I need to use product category slugs in my product permalinks so the links are to be like example.com/laptops/some-laptop

I selected the Custom base option in my Permalink Settings, typed /%product-cat%/ in the field and saved. Next I added the following code to my theme's functions.php

add_filter('post_type_link', 'category_slug_in_product_permalink', 10, 2);
function category_slug_in_product_permalink($permalink, $post) {

    if($post->post_type == 'product') { 
        $categories = wp_get_object_terms($post->ID, 'product_cat');
        $permalink = str_replace('%product-cat%', $categories[0]->slug, $permalink);
    return $permalink;

The code works fine and I see the product permalinks are now exactly as needed.

But when I click by any of the links, I receive the 400 Bad Request error. As I read by the link wordpress.stackexchange.com/a/334902 the post_type_link filter only changes urls, but "it doesn’t change any rewrite rules and the structure of permalinks is still the same".

So how can I resolve this second half of the issue?

I found mentions of $GLOBALS['wp_rewrite'], 'slug' => '%...%', 'with_front' => false and so on, but I didn't find full working solution or I just don't know how to use existing ones

2 Answers 2


Ok, so the second code is:

function custom_rewrite_basic() {

    $prodCatArgs = ['taxonomy' => 'product_cat'];
    $wooCats = get_categories($prodCatArgs);
    $catSlugs = [];
    foreach($wooCats as $wooCat) {
        $catSlugs[] = $wooCat->slug;
        '^('.implode('|', $catSlugs).')/([^/]*)/?',
add_action('init', 'custom_rewrite_basic');

Alternatively you can use my plugin and adjust the product permalinks directly from Wordpress admin dashboard.

  1. Firstly, you need to install Permalink Manager Lite from Wordpress Plugin Directory.
  2. Then you need to go to "Tools -> Permalink Manager -> Permastructures" admin page and scroll down to "Products".
  3. Now, you should replace the default permalink format with: %product_cat%/%product%
  4. The new permastructure settings will be applied to the new products only, but if you need to you can regenerate the old product permalinks in "Tools -> Permalink Manager -> Tools -> Regenerate/Reset" section.

You can find the full instructions here: https://permalinkmanager.pro/docs/tutorials/taxonomy-slugs-in-custom-post-type-permalinks/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.