Home » WooCommerce: Exclude Category from Search Results

WooCommerce: Exclude Category from Search Results

by Tutor Aspire

We’ve already seen how to only display products from a single category on the Shop page. Today, we’ll do something similar, but we’ll target the search result.

Code is somewhat similar to the example I linked to above, so it will use once again the “pre_get_posts” filter in order to modify the query before products are returned on the screen. Enjoy!

I’ve searched for “courses” here, and because the snippet below is active, no search result (WooCommerce product) will show from the “Courses” category.

PHP Snippet: Exclude Products From a Given Category @ WooCommerce Search Result Page

 * @snippet       Exclude Cat @ WooCommerce Product Search Results
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 6
 * @donate $9     https://www.tutoraspire.com

add_action( 'pre_get_posts', 'tutoraspire_exclude_category_woocommerce_search' );

function tutoraspire_exclude_category_woocommerce_search( $q ) {
   if ( ! $q->is_main_query() ) return;
   if ( ! $q->is_search() ) return;
   if ( ! is_admin() ) {
      $q->set( 'tax_query', array( array(
         'taxonomy' => 'product_cat',
         'field' => 'slug',
         'terms' => array( 'courses' ), // change 'courses' with your cat slug/s
         'operator' => 'NOT IN'

You may also like