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!

PHP Snippet: Exclude Products From a Given Category @ WooCommerce Search Result Page
/**
* @snippet Exclude Cat @ WooCommerce Product Search Results
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @compatible WooCommerce 8
* @community https://businessbloomer.com/club/
*/
add_action( 'pre_get_posts', 'bbloomer_exclude_category_woocommerce_search' );
function bbloomer_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'
)));
}
}
Advanced Plugin: WooCommerce Protected Categories
The code snippet above focusses on excluding products from a particular WooCommerce category from search results. If you’re doing this then it’s likely that you’ll also need other ways to control who can access the products from each category.
I looked for a flexible no-code way of doing this, and discovered the WooCommerce Protected Categories plugin.
This plugin from Barn2 gives you full control over product visibility on a per-category basis. For each category, you can choose which users and/or roles can access it and the products within it. There’s an option to show products from restricted categories in public areas such as search results, or you can hide them from unauthorized users completely.

Another masterpiece of code. Thanks man, really, God Bless you and your family.
Great!
PHP Snippet: Exclude Products From a Given Category @ WooCommerce Search Result Page
Hi – I got this error:
——————————————-
Your PHP code changes were rolled back due to an error on line 66 of file wp-content/themes/dt-the7-child/functions.php. Please fix and try saving again.
syntax error, unexpected ‘add_action’ (T_STRING)
———————————
WordPress version: 6.1.1
WooCommerce version: 7.1.0
PHP version: 7.3.29
What’s on line 66? Did you copy the exact snippet including comments?