How to filter WordPress search, excluding post in some custom taxonomies?

I want to filter WordPress search (and also WordPress listing of posts) on 2 values of a custom taxonomy.

I tried this code, filtering my custom taxonomy named “marque”, excluding 70 or 67 IDs (nb : in my back-office, posts can only be classified into one term of my taxonomy a time) :

Read More
// Filtering on listing
function filtre_listes( $query ) {
    if ( !is_admin() ) {
        $query->set( 'marque', '-70,-67' );
    }
    return $query;
}
add_action( 'pre_get_posts', 'filtre_listes' );

// Filtering on searches
function filtre_recherches(&$query)
{
    if ( $query->is_search && ( !is_admin() ) )
        $query->set('marque', '-70,-67');
    return $query;
}
add_action('parse_query', 'filtre_recherches');

But it doesn’t seems to work. I use WordPress 3.0.5.

Any idea ?

Thanks a lot, and sorry for my approximative english !

Related posts

Leave a Reply

2 comments

  1. Try

    $tax_query = array(
        'relation' => 'AND',
         array(
            'taxonomy' => 'marque',
            'terms' => array( 70, 67 ),
            'field' => 'term_id',
            'operator' => 'NOT IN'
          )
     );
     //turn it into a WP_Tax_Query object...
    $tax_query = new WP_TaxQuery($tax_query);
    
    $query->set("tax_query", $tax_query);
    
  2. You can exclude Posts in a Taxonomy Term from appearing in search results, archive lists and more by using the incredibly powerful pre_get_posts hook.

    Consider the following example placed in your theme’s functions.php file:

    add_action( 'pre_get_posts', function ( $query ) {
        if ( is_admin() || ! $query->is_main_query() ) {
            return;
        }
    
        // Exclude Terms by ID from Search and Archive Listings
        if ( is_search() || is_tax( 'marque' ) ) {    
            $tax_query = array([
                'taxonomy' => 'marque',
                'field' => 'term_id',
                'terms' => [ 67, 70 ],
                'operator' => 'NOT IN',
            ]);
    
            $query->set( 'tax_query', $tax_query );
        }
    }, 11, 1 );
    

    This action will exclude your terms (67, 70) in the given the taxonomy (marque) from appearing in any search results or archive lists.

    Since the $query object is passed by reference, we do not need to declare globals or return a value. Thus, any changes made to the object from inside our function are made to the original immediately.