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

May 22, 2019 | WooCommerce Tips | 0 comments

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' );

0 Comments

Submit a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.