Woocommerce: Hide subcategory products from main category | themelocation

How to hide subcategory products from main category in Woocommerce?

In this tutorial; We will learn how to hide subcategory from main category page in woocommerce. To do this, We will need to create/add two products and assign them to parent and child categories.

I’ve assigned two products, one to the parent category i.e. category 1 and the other to the child category i.e. category 1-1.

2015-07-06_1128Now after assigning products to the categories, if you’ll go to parent category page you’ll see both products from parent category as well as child category.

2015-07-06_1130Now We want to display only parent category products and remove the child category products. Add the following lines of code at the end of your theme’s functions.php file.

function exclude_product_cat_children($wp_query) {
if ( isset ( $wp_query->query_vars['product_cat'] ) && $wp_query->is_main_query()) {
    $wp_query->set('tax_query', array( 
                                    array (
                                        'taxonomy' => 'product_cat',
                                        'field' => 'slug',
                                        'terms' => $wp_query->query_vars['product_cat'],
                                        'include_children' => false
                                    ) 
                                 )
    );
  }
}  
add_filter('pre_get_posts', 'exclude_product_cat_children');

Now if you’ll go to parent category page again or just refresh the page if you already are there you’ll see the products of child category being removed from here.

2015-07-06_1134That is It.

3 Responses to How to hide subcategory products from main category in Woocommerce?

  1. Sean November 18, 2015 at 9:41 am #

    Thank you!

  2. Steve September 24, 2016 at 2:30 pm #

    Hello,

    Your fix works, but it means that the WooCommerce Layered Nav Widget no longer filters the products correctly. Can you help?

  3. Rafi Haidari March 20, 2017 at 7:18 am #

    It works charming for me, thank you for sharing it.

Leave a Reply