How-to exclude terms from the main query the most performant way?

This Q is a follow up to this answer on the Q: “How to exclude a specific term for the search?”.

4 ways to filter out posts that have a specific term

Type                | Pro                   | Contra
--------------------------------------------------------
Run a new query     | Easy to implement     | Add. Queries
                                            | Add. time to execute the DB call + processing the parsing of the results
Inside the loop     | Easy to implement     | Sometimes Add. Queries
                                            | Add. time to execute
Modify the query    | Full control          | Hard to implement
                                            | Needs a lot of knowledge (preparing, DB interaction)
Add new query parts | No perform. impact    | Hard to get around
                    | Secure
                    | Full core support

The first type imho is not an option. The “Types” 2 & 3 are already answered in the other Q and both still have some backdraws.

Question:

  1. How to add an additional tax_query argument to the main query using (for e.g.) the pre_get_posts filter?
  2. Do you know additional ways to modify the main query?

1 Answer
1

You can set the taxonomy query for the main query using pre_get_posts:

add_action( 'pre_get_posts', 'my_exclude_terms_from_query' );
function my_exclude_terms_from_query( $query ) {
    if ( $query->is_main_query() /* && whatever else */ ) {
        $tax_query = array (
                array(
                    'taxonomy' => 'category',
                    'terms' => array( 'cat-slug' ),
                    'field' => 'slug',
                    'operator' => 'NOT IN',
                )
        );
        $query->set( 'tax_query', $tax_query );
    }
}

If tax_query is already set and you need to modify it instead, you can grab and then add to the $tax_query array.

Leave a Comment