The first thing we need to do to use add the code snippet that will prevent WooCommerce Hidden Products Showing in Search Results is to open the functions.php file.

There are many different ways you can edit functions.php file but the best way is using the Theme Editor option on the WordPress dashboard.

  1. Open functions.php file.

After logging into the WordPress dashboard, choose the Appearance menu from the left sidebar and then click on the Theme Editor sub-menu.

Then click on the functions.php under the Theme Files title on the right side to open it on the theme editor.

functions.php file opened in WordPress dashboard Theme Editor

  1. Adding the code snippet

After scrolling down to the bottom of functions.php file, copy the following code snippet and paste it at the end of the functions.php


add_action('pre_get_posts', 'wpse_search_query_pre');
function wpse_search_query_pre($query) {
if ($query->is_search() && $query->is_main_query()) {
$tax_query = $query->get('tax_query', array());
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'exclude-from-catalog',
'operator' => 'NOT IN',
);
$query->set('tax_query', $tax_query);
}
}

This is all you need to do to prevent hidden WooCommerce products from unexpectedly showing up in the search results. Please let us know if this doesn’t work for you.