(Moderators note: Was originally titled “How to get_posts of a custom post type that is in two custom taxonomies?”)
I have a custom post type that has two taxonomies which are separate, one called “Project Type” and one called “Package”. I need to get a list of projects which are of “Project Type” A
and “Package” A
. I tried using following code:
$args = array(
'post_type' => 'portfolio',
'numberposts' => -1,
'project_type' => 'A',
'package' => 'A'
);
$my_posts = get_posts($args);
But this gets all the posts that are EITHER in Project Type A OR Package A.
Is there any way to say in get_posts()
that I want to return only those posts that are in BOTH taxonomies?
As of v1.3, the Query Multiple Taxonomies plugin works great with WP_Query. Your original args work as is.
Then make a new query and check it:
I tested this on my own custom taxonomy setup, and it only returned posts which matched both terms in the query.
Another convenient method of grabbing multiple taxonomy terms with QMT is building simple URL queries:
I’ve used this method with the
add_query_args()
function to create links on a page that modify the current query, refining it by adding additional terms and taxonomies. The syntax also works great with a search input, as multiple words in the input field are posted as foo+bar, which works great with QMT:Which returns only posts that meet all these criteria – Type: Portfolio / Project: Alpha / Colors: red + blue + green
Hi @shaun:
@Rarst is right in that they are adding this functionality to WordPress v3.1, but it won’t be here for a while and I’m sure you need it now. You could try to grab the code they are working on and try to make it work, you could use the plugin both @Rarst and @somatic mention, or you could just include the code you need into your theme, below.
The following code is a
posts_where
hook to add atax_terms
query variable with a value of the format (i.e. colon-commas) where the values are term slugs:This is a self-contained
.php
you can drop into the root of your website to test it out before pulling theadd_action
call and thetax_terms_where()
function into your theme’sfunctions.php
file (or into the.php
file of one of your own plugins.)If this isn’t exactly what you need because, for example, you’d rather match the
$term->term_id
instead of matching the$term->slug
then the code shouldn’t be too hard to modify for your needs, assuming you are comfortable with SQL and.php
.Old Q, but apparently comes up so here is current state â taxonomy queries got much improved in 3.1 and further since.
These days it will easily be handled with tax query using
AND
relationship, example from Codex:See Taxonomy Parameters for full documentation.
Usual disclaimer – I hadn’t messed with custom stuff myself so far.
I think complex taxonomy queries are not implemented in WP core (yet). Try Query Multiple Taxonomies plugin.