Getting the Intersection of Two Custom Taxonomy Terms for a Custom Post Type?

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

3 s
3

As of v1.3, the Query Multiple Taxonomies plugin works great with WP_Query. Your original args work as is.

$args = array(
'post_type' => 'portfolio',
'numberposts' => -1,
'project_type' => 'A',
'package' => 'A'
);

Then make a new query and check it:

$foo = new WP_Query($args);
var_dump($foo->posts);

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:

site.com/?post_type=portfolio&package=foo&project=bar

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:

site.com/?post_type=portfolio&project=alpha&colors=red+blue+green

Which returns only posts that meet all these criteria – Type: Portfolio / Project: Alpha / Colors: red + blue + green

Leave a Comment