Remove products of a specific category from search results in Woocommerce?

In this tutorial; We’ll learn how to remove products of a specific category from search results in Woocommerce.

I’ve some products in my store starting with the text “product”.

Now, when I searched for the word “product”, I received 6 products.

woocommerceNow let’s say I want to exclude those products which are in “category-2” from these search results.

To do this, add the following lines of code at the end of your theme’s functions.php file:

function wpse188669_pre_get_posts( $query ) {

   if (

       ! is_admin()

&& $query->is_main_query()

&& $query->is_search()

   ) {

       $query->set( 'post_type', array( 'product' ) );

       // set your parameters according to

     // https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

       $tax_query = array(

           array(

               // likely what you are after

               'taxonomy' => 'product_cat',

               'field'   => 'slug',

               'terms'   => 'category-2',

               'operator' => 'NOT IN',

           ),

       );

       $query->set( 'tax_query', $tax_query );

}

}

add_action( 'pre_get_posts', 'wpse188669_pre_get_posts' );

You can access functions.php file here:

woocommerceAnd now if we search term product again, we’ll see products of category-2 has been removed from the search results.

Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

3 thoughts on “Remove products of a specific category from search results in Woocommerce?”

Leave a Comment

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