How to prevent hidden WooCommerce products from showing up in WordPress search results

WooCommerce Tips

Add the function below to your child theme functions.php file.

/* Preventing Hidden WooCommerce products from showing up in WordPress search results */
if ( ! function_exists( 'gamma_search_query_fix' ) ){
  function gamma_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', 'gamma_search_query_fix' );