0

I'm looking for a way to exclude a product category from search results with Woocommerce using the pre_get_posts action and $query->set(). I am searching using the Wordpress ?s=keyword search. I know that the function will begin like this:

add_action('pre_get_posts', 'exclude_product_category');
function exclude_product_category( $query ) {

    global $wp_the_query;

    if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_search() ) ) {
       // more code goes here
    }
    return $query;
}

I want to specify something like this:

query_posts( array(
    'post_type' =>'product',
        'tax_query' => array(
           array(
               'taxonomy' => 'product_cat',
               'field' => 'id',
               'terms' => array(18),
               'operator' => 'NOT IN',
               ),
        )
     ));    

How would I accomplish this?

1 Answer 1

1
function exclude_product_category( $query ) {

    if ($query->is_search()) {
        $tax_query = (array) $query->get('tax_query');

        $tax_query[] = array(
               'taxonomy' => 'product_cat',
               'field' => 'slug',
               'terms' => array('excluded-category'),
               'operator' => 'NOT IN'
        );        
        
        $query->set('tax_query', $tax_query);        

    }
    return $query;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.