skip to Main Content

when I enter a category it shows me all the subcategories and the products in the subcategories. I want to show only the subcategories and hide the products of these.

I have used this code but it does not show me the subcategories if there is no product added from the main category.

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'); 

If there is no product in the main category, it does not show the subcategories.
View image

Here I add a product to the main category and show the subcategories.
View image

I would like to show the subcategories even if there are no products in the main category. Thank you very much for your help.

2

Answers


  1. You are already on the way by using the pre_get_posts hook.

    Here is what you can do:

    function hide_products_in_subcategories($query) {
      // Check if we are on a category archive page
      if ($query->is_tax('product_cat') && $query->is_main_query()) {
        // Set the number of products per page to 0
        $query->set('posts_per_page', 0);
      }
    }
    add_action('pre_get_posts', 'hide_products_in_subcategories');
    
    Login or Signup to reply.
  2. This is the exact quirk I want to fix. It’s weird this isn’t a setting. Seems obvious.

    UPDATE
    Found the fix! Added this to functions.php and all is well.

    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');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search