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