Wordpress Tip: Posts From Multiple Categories
I have been in the thick of Wordpress code for the past week, and have learned quite a bit about this pile of open source goodness. I’m continually amazed at how many “problems” have already been solved and offered up to the community as a free gift. Often the most challenging bit is that a problem has been solved a number of ways, and you’re forced to choose between two “right” solutions.
Today, I had to solve the “posts from multiple categories” challenge: show a post that had been filed under two specific categories. Documentation was slim. And in fact, not many people were asking for it. Luckily one person did, and another answered, but considering how difficult it was for me to find it, I thought I’d mention it again.
The forum post linked above was asking how to get it from query_posts(), but I needed to use it when constructing a WP_Query object. But the solution fits for each of course. Both receive your lookup conditions the same two ways (either as a string formatted as a $_GET query string, or by an array). The trick is that to get this to work, you need to pass your query by array.
Ready? Here it is:
query_posts(array('categories__and' => array(1, 2)));
This tells Wordpress to look for any post that has been filed under two categories, one with an ID value of 1, the other with an ID of 2.
In case you’ve tried this:
query_posts('cat=1,2');
This essentially performs an OR statement, or more precisely, an IN(1,2) condition.
Happy wordpressing!