Skip to content

Instantly share code, notes, and snippets.

@ChrisFlannagan
Last active October 9, 2022 12:12
Show Gist options
  • Save ChrisFlannagan/f79ab49491c2b85b0925c66a7fe971fd to your computer and use it in GitHub Desktop.
Save ChrisFlannagan/f79ab49491c2b85b0925c66a7fe971fd 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 );
}
}
@egbamddeveloper
Copy link

Very good, thanks :)
Save my time..

You need to remove public in line 2.
And [] in line 10.

@andreacreativesoft
Copy link

Hello, Chris - any idea why it will not work on the Category display also? looks like they are still taken in the loop on those

@JaviPalla
Copy link

JaviPalla commented Oct 8, 2022

Thanks, saved a lot of time with this function!
By the way I had to make some changes. When tax_query is empty API was throwing me an exception, I had to check whether 'tax_query' was string or array :

if (gettype($tax_query) === 'string') {
			$tax_query = [];
		}

I have no experience with PHP, maybe it is a better way to fix this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment