2
votes

I have 2 product categories "current-probes" and "accessories" that have some subcategories "flex-ct", "tlar" and "test-lead" .

I would like to display in the shop page, my subcategories and my products. I know that WooCommerce has a setting to display the parent categories and products but not the subcategories.

I also need to prevent the individual products of the subcategories from displaying.

Here is the code that I have tried (located in my functions.php file):

add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $q ) {
if ( ! is_admin() && is_shop() || is_product_category( array( 'current-probes', 'accessories' ))  ) {
    $q->set( 'tax_query', array(array(
        'taxonomy' => 'product_cat',
        'field' => 'slug',
        'terms' => array( 'flex-ct', 'tlar', 'test-lead' ), 
        'operator' => 'NOT IN'
    )));
}

remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}

This prevents the individual products of the subcategories from showing, but I need the actual subcategory to show up in the loop.

WooCommerce has a setting that displays categories and products only, basically I would like that only it is displaying the subcategories (not the parent categories) and the products. I hope that makes sense.

I have been trying to figure this out for a week and I am going crazy. I feel like there is a simple solution that I have just overlooked.

What I am doing wrong? How can I achieve this?

Thanks

1
I'm checking that out and I can see how I could do the multiple taxonomy handling. I'm still not sure how I get the subcategory though, not the main category and not the individual posts for them. Can you point me in the right direction? I sincerely appreciate your help.Kate The Dev
There was a syntax error in that snippet that I fixed but that is not what I am looking for. Thank you for your help though.Kate The Dev

1 Answers

0
votes

I have found what I am looking for, almost. It is actually not using the pre_get_posts. Here is the code:

add_filter( 'woocommerce_product_subcategories_args', 'filter_woocommerce_product_subcategories_args', 10, 1 ); 
function filter_woocommerce_product_subcategories_args( $array ) { 
if ( ! is_admin() && is_shop() ) {
    $category = get_term_by('name', 'Products', 'product_cat');
    $parent_id = ($category) ? $category->term_id : 10;
    $array['parent'] = $parent_id;

        return $array; 
}; 
}

This will output the subcategories of category 10. My only problem is that I need to pick more than one parent category. I am not familiar with using this syntax with the colons so I'm not sure how to specify more than one parent category. Also this prevents the subcategory from displaying on its parents category page, which I don't want that to happen either. If anyone has some feedback it would be most appreciated.