WooCommerce Hidden Products in WordPress Search Results

One of the little WooCommerce issues our clients often run into is that WordPress does not acknowledge product visibility setting in Woo and shows hidden product in Search results.  Here is the little snippet that takes care of that issue. The code should be placed in functions.php file of your WordPress theme.

/* GammaFX: 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' );