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.
Now 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:
And now if we search term product again, we’ll see products of category-2 has been removed from the search results.
Thank you very much for this explanation!
Exactly what I needed. Thanks very much!!
Thank you, it worked like a charm.