Hiding child products in WooCommerce parent product column category table
According to the default logic of the WooCommerce plugin, products in the child category will automatically appear in the parent category's product list. According to common sense, this is the correct display logic, since a product belongs to a subcategory, it must also belong to the parent category, just like Chaoyang District belongs to Beijing, it must also belong to China. However, in some projects, there is no need for such a display. On the parent product list page, only the products in the sub-category and parent category are displayed. There is no such setting in the category settings of WooCommerce, but we can directly modify the WooCommerce product query to realize this function.
Modify the main query to hide the child products in the list of parent products.
Directly add the following code to the theme's functions.php to achieve this function. It is not difficult to see that the following code, the main role of the'include_children' => false,This line, meaning tell the product query, in the current query, do not include the products in the subcategory.
add_filter('pre_get_posts', function ($wp_query)
{
if (isset ($wp_query->query_vars[ 'product_cat' ]) && $wp_query->is_main_query()) {
$wp_query->set('tax_query', [
[
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $wp_query->query_vars[ 'product_cat' ],
'include_children' => false, .
]
]
);
}
}).;Based on the principle in the above code, we can customize the WooCommerce product list more, just put the modified query parameters here as needed.