I try to create a custom permalink for products in a specific product category but it works really weird.
I try to achieve URLs like:
- domain.com/category_name/product-name - for products in a specific category,
- domain.com/default_slug/product-name - for the rest of products
I tried to add the %type% rule to product permalinks by using a two-step approach to (1) generate proper URLs and (2) show respective product page:
function custom_permalink($permalink, $post_id, $leavename) {
if (strpos($permalink, '%type%') === FALSE) return $permalink;
// Get post
$post = get_post($post_id);
if (!$post) return $permalink;
// Get taxonomy terms
$terms = wp_get_object_terms($post->ID, 'product_cat');
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) {
if ($terms[0]->slug == 'category_name') {
$taxonomy_slug = $terms[0]->slug;
} else {
$taxonomy_slug = 'default_slug';
}
}
else {
$taxonomy_slug = 'default_slug';
}
return str_replace('%type%', $taxonomy_slug, $permalink);
}
add_filter('post_link', 'custom_permalink', 10, 3);
add_filter('post_type_link', 'custom_permalink', 10, 3);
function rewrite_product_base_tag() {
add_rewrite_tag( '%type%', '([^&]+)', 'in-type=' );
}
add_action( 'init', 'rewrite_product_base_tag', 10, 0 );
It works fine except it shows products even if I use any random slug. The following URLs will show the product based on its name (every single URL shows the "product-name" product):
- domain.com/default_slug/product-name
- domain.com/category_name/product-name
- domain.com/ANY_RANDOM_STRING/product-name
I also tried to use different regex to limit available slugs. It only shows the second option (category_name) properly. The first one (default_slug) shows the Archive page. It works exactly the same even if those are changed with each other: the first one shows the Archive page, the second one works fine.
Adding a rewrite_rule function doesn't work at all.
function rewrite_product_base_tag() {
add_rewrite_tag( '%type%', '(default_slug|category_name)', 'in-type=' );
}
add_action( 'init', 'rewrite_product_base_tag', 10, 0 );