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


if ( ! function_exists( 'woo_hidden_search_query_fix' ) ){
function woo_hidden_search_query_fix( $query = false ) {
if(!is_admin() && is_search()){
$query->set( 'meta_query', array(
'relation' => 'OR',
array(
'key' => '_visibility',
'value' => 'hidden',
'compare' => 'NOT EXISTS',
),
array(
'key' => '_visibility',
'value' => 'hidden',
'compare' => '!=',
),
));
}
}
}
add_action( 'pre_get_posts', 'woo_hidden_search_query_fix' );

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.