Woocommerce: display parent category (is any) instead of current category

Creating a custom theme, I have to alter the way WooCommerce behaves when displaying a product category.

The default behavior is to display subcategories and/or products for user-selected category. For example subcategories and/or products for sub-sub-category_a when requesting https://wordpress_site/product-category/category_a/sub-category_a/sub-sub-category_a/

What I want to achieve is to either:

  • keep the default behavior if current category has no parent (ie https://wordpress_site/product-category/category_a)
  • alter the default behavior if current category has a parent (https://wordpress_site/product-category/category_a/sub-category_a/sub-sub-category_a/) and instead display the products for the parent category sub-category_a instead of the products for the current category sub-sub-category_a

In my opinion, I have to alter the $wp_query when archive-product.php template is called, but I have no clue how to achieve this the right way. Could you please help me?

To answer the question "why?", the aim is top add a select box with the children categories on top of the page and dynamically filter the product list client side to either only show products for the selected category or all the products if none or an "all categories" option is selected.


  • Miss

    So basically, if a product category has a parent, you want to retrieve all products for the parent category.

    To achieve this you need to edit the query, along these lines:

    function prefix_get_parent_category_products( $query ){
        // check we're in the right place and the category has a parent
        if( $query->is_tax('product_cat') && !empty($query->query_vars['post_parent']) ){
            // edit the tax query to include the parent category
            $query->set('tax_query', array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $query->query_vars['post_parent'],
                'include_children' => true
    add_action( 'pre_get_posts', 'prefix_get_parent_category_products' );

    Note, I've not tested this function so you may need to adapt to your needs.

    Hope that helps!

Add Comment