How to Hide Child Category Products from WooCommerce Parent Category Lists

By default, WooCommerce automatically includes products from subcategories in the product list of their parent category. Logically, this makes sense: if a product belongs to a subcategory, it inherently belongs to the parent category as well. However, in some projects, you may want to disable this behavior and only display products directly assigned to the specific category being viewed. While WooCommerce doesn’t provide a built-in setting for this, we can easily achieve it by modifying the main WooCommerce product query.

Modifying the Main Query to Hide Subcategory Products

You can implement this functionality by adding the following code snippet to your theme’s functions.php file. The key line in this code is 'include_children' => false,, which instructs the product query not to include products from any child categories during the current request.

add_action('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 demonstrated above, you can further customize WooCommerce product lists by adjusting the query parameters to meet your specific store requirements. Simply modify the tax query or other query variables within this filter as needed.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *