How to remove subcategory products from the main category page

by | Oct 6, 2021 | Code Snippets | 0 comments

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.

By Abdou

My name is Abdelfatah Aboelghit, a PHP developer from Egypt and my friends call me Abdou!
Here I write and develop products about Divi Theme.

More Article

0 Comments

Submit a Comment

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

Shop Tabs Plugin

A must-have plugin for Divi & WooCommerce.

Read More

Divi Theme

The Best Theme For WordPress. 

Read More

Pin It on Pinterest

Share This