The most popular ecommerce plugin, WooCommerce, has very few customizations for advanced shop owners. That is, if you need something non-standard, you won’t be able to implement it by pressing a button or a checkbox. But (!) no one says that this is impossible. You just need the help of a programmer.

Change the logic for displaying products in WooCommerce depending on the category

The next request from the client was just that. The client did not find where in WooCommerce it is possible to turn off the display of products from the final category in the main category.
Let’s rephrase the problem: do not show products from a subcategory in the parent category.
To be more precise: display products exclusively in their category.

For obvious reasons, the standard “Customize appearance” is not suitable here. The request is non-standard and requires a non-standard solution.

On the Internet, you will find several solutions to similar problems using the pre_get_posts hook, but not all of them work.

So, to prevent subcategories from showing products in the main category, add this code (source) to the end of your child theme’s functions.php file:

// Speedplus.com.ua HIDE SUBCATEGORIES PRODUCTS
add_action('parse_tax_query', 'speedplus_filter_subcat_goods'); 
function speedplus_filter_subcat_goods( $query ) {
    if ( is_tax( 'product_cat' ) ) {
        $queried_object = get_queried_object();
        $child_cats     = (array) get_term_children( $queried_object->term_id, 'product_cat' );
        if ( ! $query->is_admin ) //exclude the posts in child categories
        {
            $query->tax_query->queries[] = [
                'taxonomy' => 'product_cat',
                'field'    => 'term_id',
                'terms'    => array_merge( $child_cats ),
                'operator' => 'NOT IN'
            ];
        }
    }
}

If you need a programmer’s help with this or any other WordPress or Woocommerce task, you can create a personal project on Freelancehunt or write us a message.

Leave a comment

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