Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebacruz/a90cad1d1c8b6b455c89907407db5523 to your computer and use it in GitHub Desktop.
Save sebacruz/a90cad1d1c8b6b455c89907407db5523 to your computer and use it in GitHub Desktop.
Woo doesn’t filter out products with hidden catalog visibility outside of main shop loop. This is important to remember when using the REST API for front end display or general search results. This code snippet will keep them from showing outside of the admin. Source: whoischris.com
<?php
/**
* https://whoischris.com/remove-catalog-visibility-hidden-products-in-woocommerce-from-search-wp-rest-api-results/
*/
add_action( 'pre_get_posts', 'hidden_search_query_fix' );
public function hidden_search_query_fix( $query = false ) {
if ( ! is_admin() && isset( $query->query['post_type'] ) && $query->query['post_type'] === 'product' ) {
$tax_query = $query->get( 'tax_query' );
$tax_query[] = [
'relation' => 'OR',
[
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'exclude-from-catalog',
'operator' => 'NOT IN',
],
[
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'exclude-from-catalog',
'operator' => '!=',
],
];
$query->set( 'tax_query', $tax_query );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment