Knowledge Base

Filtering WooCommerce hidden catalog products

in Ajax Search Pro Tips Tags: invisibleproductwoocommerce

WooCommerce uses a custom field to mark product visibility. These products stay published and accessible, but they are hidden from the catalog.

Since the published status is not affected, the search query cannot recognize if the product is hidden or not, additional post-processing is required.

To filter hidden products, put this small code snippet to your Themes functions.php file:

add_filter( 'asp_results', 'filter_asp_results', 1, 1 );

function filter_asp_results($results){

  /* If the results are grouped */
  if (isset($results['grouped'])) {
    foreach ($results['items'] as $i_k=>$data) {
        if ($i_k == 'name') continue;
        
        // $result['data'] holds the results here                
        foreach($results['items'][$i_k]['data'] as $r_k => &$result) {

          if (asp_unset_if_hidden($result))
            unset($results['items'][$i_k]['data'][$r_k]);
          
        }      
    }
    /**
     *  You need to return the $results variable here,
     *  since the changes are made directly  
     **/     
    return $results;
  
  /* Non-grouped */  
  } else {
      foreach($results as $k => &$result) {

        if (asp_unset_if_hidden($result))
          unset($results[$k]); 
          
      }

      return $results;
  }
}

function asp_unset_if_hidden( $v ) {
  // Visibility key in WooCommerce
  $key = '_visibility';
  
  if (!isset($v->post_type) || $v->post_type != 'product') return false;
  $visibility = get_post_meta( $v->id, $key, true );
  if ($visibility != 'visible') 
    return true;
  
  return false;
}