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


       $tax_query = 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.

About the author

We provide WordPress & WooCommerce Support, Maintenance and Development Services.
3 Responses

Leave a Reply

Get New WordPress & WooCommerce Code Snippets! (Weekly)

We find new codes snippets to improve your existing Websites.