I have a taxonomy template that display products from both parent and child terms, how can I show only the products belonging to the parent terms?

I'm trying to modify somehow this part of code:

            <?php woocommerce_product_subcategories(); ?>

            <?php while ( have_posts() ) : the_post(); ?>

                <?php wc_get_template_part( 'content', 'product' ); ?>

            <?php endwhile; // end of the loop. ?>

        <?php woocommerce_product_loop_end(); ?>

and how can I show only the products that belong to the current taxonomy?


you 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() ) {
            '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');
  • Thank you very much, Patel Jignesh, i googled this code before asking question, tried this, modified functions.php but had no luck - simply doesn't work at all. I dont know why. maybe there is interferention between this filter and "woocommerce product filter" plugin =( – Yury Zheve Jul 31 '17 at 18:29
  • i am testing this code is work fine for me. you can add priority into filter hook. add_filter('pre_get_posts', 'exclude_product_cat_children',99); i hope it's work – Jignesh Patel Aug 1 '17 at 3:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.