Exclude a term of a taxonomy with a custom post type in a search

I’ve got a WooCommerce category for sold items within WooCommerce’s custom post type of ‘product’. What I’m trying to do is have the site search only return results from the product post type but also exclude the sold items category. Any code I seem to find to exclude categories from search doesn’t seem to work but I’m guessing that’s because it’s a category within a CPT.

The code I’ve got for filtering searches down to just to the product CPT (in functions.php):

function mySearchFilter($query) {
    $post_type = $_GET['type'];
    if (!$post_type) {
        $post_type="product";
    }
    if ($query->is_search) {
        $query->set('post_type', $post_type);
    };
    return $query;
};

And the code I’ve tried to exclude categories:

function remove_categories_wp_search($query) {
if ($query->is_search) {
    $query->set('cat','-247');
}
    return $query;
}
add_filter('pre_get_posts','remove_categories_wp_search');

Any ideas?

EDIT:
As per ialocin’s suggestion I also tried:

function wpse188669_pre_get_posts( $query ) {
    if ( 
        ! is_admin() 
        && $query->is_main_query() 
        && $query->is_search() 
    ) {
        // set your parameters according to
        // https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
        $tax_query = array(
            // likely what you are after
            'taxonomy' => 'sold-gallery',
            'operator' => 'NOT IN',
        );
        $query->set( 'tax_query', $tax_query );
  }
}
add_action( 'pre_get_posts', 'wpse188669_pre_get_posts' );

2 Answers
2

The problem with your approach is that woocommerces product category is a custom taxonomy called product_cat. But with cat you are addressing the built-in category. Taxonomies can be addressed with a tax query, simplified example below:

function wpse188669_pre_get_posts( $query ) {
    if ( 
        ! is_admin() 
        && $query->is_main_query() 
        && $query->is_search() 
    ) {
        $query->set( 'post_type', array( 'product' ) );
        // set your parameters according to
        // https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
        $tax_query = array(
            array(
                // likely what you are after
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => 'sold-gallery',
                'operator' => 'NOT IN',
            ),
        );
        $query->set( 'tax_query', $tax_query );
  }
}
add_action( 'pre_get_posts', 'wpse188669_pre_get_posts' );

Leave a Comment