Including all terms in wordpress tax_query

I’m a little bit confused, why I can’t include all the terms in tax_query automatically?

My code:

Read More
'tax_query' => array(
    array(
        'taxonomy' => 'city',
        'field' => 'slug',
        'terms' => array( nyc, boston, london ),
         )
)

What If I’ve dozens of cities? Isn’t it uncool to add them all manually?

Related posts

Leave a Reply

3 comments

  1. Unless you have posts that don’t have a city aren’t you essentially querying all your posts? Anyway, Eric Holmes is correct that you should be using WP_Query in lieu of query_posts().

    That said, you can get a list of all the terms in a taxonomy and then use those values in your tax query.

    // get all terms in the taxonomy
    $terms = get_terms( 'city' ); 
    // convert array of term objects to array of term IDs
    $term_ids = wp_list_pluck( $terms, 'term_id' );
    
    // proceed with tax query
    $args = array ('tax_query' => array(
        array(
            'taxonomy' => 'city',
            'field' => 'term_id',
            'terms' => $term_ids,
             )
    )
    );
    
    $city_posts = new WP_Query( $args );
    
  2. In addition to the marked ‘best answer’, there is another way which might be even faster because we don’t have to pull the terms and extract the names first.

    This is achieved with a trick by using a non-existing operator (none of ‘IN’, ‘NOT IN’, ‘AND’, ‘EXISTS’ and ‘NOT EXISTS’). For example, the string ‘XXX’ does the job and causes WP to not enter the cases during the query generation and therefore also the 0=1 concatenation is skipped.

    (The cases are located in the function get_sql_for_clause() of the file class-wp-tax-query.php, where the allowed operators are checked via conditions and there is no ‘else’.)
    .

    $args = array ('tax_query' => 
         array(
             array(
                  'taxonomy' => 'city',
                  //'field' => 'term_id', // <-- not needed, default
                  //'terms' => $term_ids, // <-- not needed
                  'operator' => 'XXX'     // Use a non-existing operator
             )
         )
    );
    
  3. Firstly, don’t use query_posts. Create a new WP_Query object instead.

    Secondly, why would you need to add all the categories, if you are literally adding ALL categories? Would this not be the same as getting all posts? You can also specify which to NOT include. ie. “Everything but Chicago”.