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()
            '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(
            '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;

            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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.