WordPress 3.1 is out, and it has some really cool new features. One of those new features is particularly useful for developers: querying multiple taxonomies.
Prior to 3.1, whenever we did a database query, and we wanted to limit the results to only posts tagged with “garden”, we were fine. But what if we wanted to display only posts tagged with “garden” AND categorized under “nature”. Well, we were out of luck.
But no more.
Setting it up is pretty simple. There is a new query_posts() parameter called “tax_query”.
Getting Posts with “garden” AND “lake”
1 2 3 4 5 6 7 8 9 10 11 12 13 | $myquery['tax_query'] = array( array( 'taxonomy' => 'category', 'terms' => array('nature'), 'field' => 'slug', ), array( 'taxonomy' => 'post_tag', 'terms' => array('garden'), 'field' => 'slug', ), ); query_posts($myquery); |
This will display all posts that are tagged with “garden” and categorized in the “nature” category.
Excluding All Posts Categorized in Either Category
1 2 3 4 5 6 7 8 9 | $myquery['tax_query'] = array( array( 'taxonomy' => 'category', 'terms' => array('nature', 'city'), 'field' => 'slug', 'operator' => 'NOT IN', ), ); query_posts($myquery); |
This will display all posts except those in either the “nature” OR “city” category.
Displaying Posts from One OR the Other
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $myquery['tax_query'] = array( 'relation' => 'OR', array( 'taxonomy' => 'category', 'terms' => array('nature'), 'field' => 'slug', ), array( 'taxonomy' => 'post_tag', 'terms' => array('garden'), 'field' => 'slug', ), ); query_posts($myquery); |
This will display all posts that are tagged with “garden” OR categorized in “nature”.
These are just a couple of examples of how we can use the new tax_query parameter available in WordPress 3.1. If you’re a developer, have you started using this feature? Do you plan to?
Enjoy!






I do not know how to implement in get_terms
$terms = get_terms($myquery); $count = count($terms); is wrong ...
i want count my post with “garden” AND “lake”
- spam
- offensive
- disagree
- off topic
Like