On category pages, WooCommerce displays the products from this page’s category and the products from its subcategories as well.
For example, if you have a main category called “Clothing” with three products, and a subcategory under this clothing category called “T-shirts,” which has another three products. When you open the “Clothing” category page on the front-end, it will display six products; 3 from the main category and three from the subcategory.
Use the following PHP code snippet if you want to remove subcategory products from the main category page.
You should add it to your child theme’s functions.php file, or you can use the Code Snippets plugin to add it via your WordPress website’s back-end.
/**
* Remove the subcategory products from the main category page
* @author Abdelfatah Aboelghit
* @version 1.0.0
*/
function dk_exclude_subcategory_products($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', 'dk_exclude_subcategory_products');
That’s it. Let me know if the code works for you in the comments.
0 Comments