4

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?
6

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.

  • That's a pretty good approach and mostly overseen. +1. As there are no other answers so far, I'll set this is as solution. Thanks! :) – kaiser Feb 20 '12 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.