Skip to content

Instantly share code, notes, and snippets.

@yanknudtskov
Created February 10, 2020 07:38
Show Gist options
  • Save yanknudtskov/f32c8e13523c28c02e83f7df5c62e529 to your computer and use it in GitHub Desktop.
Save yanknudtskov/f32c8e13523c28c02e83f7df5c62e529 to your computer and use it in GitHub Desktop.
Filter out products from search if they are hidden from catalogue as WooCommerce doesn't do this per default.
<?php
add_action( 'pre_get_posts', 'set_posts_per_page' );
function set_posts_per_page( $query ) {
if( !is_admin() ) {
if( is_search() ) {
$tax_query = (array) $query->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'slug',
'terms' => array( 'exclude-from-search', 'exclude-from-catalog' ),
'operator' => 'NOT IN'
);
$query->set( 'tax_query', $tax_query );
}
}
return $query;
}
add_action( 'woocommerce_product_query', 'yanco_woocommerce_custom_pre_get_posts_query' );
function yanco_woocommerce_custom_pre_get_posts_query( $query ) {
if( !is_admin() ) {
if( is_search() ) {
$tax_query = (array) $query->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_visibilty',
'field' => 'slug',
'terms' => array( 'exclude-from-search', 'exclude-from-catalog' ),
'operator' => 'NOT IN'
);
$query->set( 'tax_query', $tax_query );
}
}
return $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment