I need some help on category display option for Woocommerce.
In the Wordpress dashboard, I followed the below links to set up the category display option globally.
Appearance -> Customize -> Woocommerce -> Product Catalog -> Category display
There are three display options available.
- Show products
- Show subcategories
- Show subcategories & products
Currently, the third option is selected and it shows subcategories and all the products under parent categories and subcategories. However, I want to exclude all the products under subcategories. In other words, I want to show subcategories and products under parent categories only.
I found the following snippet at several tutorial sites. The code works exactly the way I want but it also disables the admin products search and filter function (it returns no results regardless).
Any idea why it happens?
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');
WP: v4.9.5 / Woocommerce: v3.3.4 / Theme: Storefront v2.2.8