How To In Woocommerce Hide Subcategory Products From Showing In Parent Category
If You building a new WooCommerce site and would like to make it so the products in subcategories don’t actually show up in the parent category just the subcategory itself. By default WooCommerce show products in parent categories, and this may make it difficult for the customer to not get confused in the products and categories.
Here is the snippet I recommend. I tested it on my own. Add this code in functions.php and products will not appear in parent categories
function exclude_product_cat_children($wp_query) {
if(!$wp_query->is_admin) {
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');


