Routing for a post type archive with custom taxonomy as a url parameter

Essentially, I have a custom post type product and it uses a taxonomy product-categories. I currently have my routing configured to use the top level category as part of a product url, e.g products/category/product, then obviously products goes to the product archive page. However, i’d like to use the category as a filter on this, for example products/category still goes to the product archive page, but with category as a parameter to use in my post query.

Here’s the current setup:

function register_product_taxonomies()
{
register_taxonomy(
‘product-category’,
array(
‘case-study’,
‘post’,
‘product’
),
array(
‘hierarchical’ => true,
‘show_ui’ => true,
‘show_admin_column’ => true,
‘label’ => __(‘Product Categories’),
‘query_var’ => true,
‘rewrite’ => array(
‘slug’ => ‘product-category’,
‘with_front’ => false
)
)
);
}

add_action(‘init’, ‘register_product_taxonomies’);

function custom_post_types()
{
$post_types = array(
array(
‘name’ => ‘Products’,
‘singular_name’ => ‘Product’,
‘menu_icon’ => ‘screenoptions’,
‘supports’ => array(‘title’, ‘editor’, ‘excerpt’, ‘thumbnail’),
‘rewrite’ => array(‘slug’ => ‘products/%product-category%’, ‘with_front’ => false),
‘has_archive’ => ‘products’
)
);
}

add_action(‘init’, ‘custom_post_types’);

function rewrite_product_permalinks($post_link, $post)
{
if (is_object($post) && $post->post_type == ‘product’){
$terms = wp_get_object_terms($post->ID, ‘product-category’);
if ($terms) {
$termSlug = $terms[0]->slug;

foreach ($terms as $term) {
if ($term->parent === 0) {
$termSlug = $term->slug;
break;
}
}

return str_replace(‘%product-category%’, $termSlug, $post_link);
}
}

return $post_link;
}

add_filter(‘post_type_link’, ‘rewrite_product_permalinks’, 1, 2);

Would I need to add a rewrite rule or is there a better way?

Read more here:: Routing for a post type archive with custom taxonomy as a url parameter

Leave a Reply

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