Sunday, April 19, 2015

Wordpress: posts linked to many categories at the same time

in some search cases, there a need to get posts linked to many categories at the same time,
this query is useful
       $whereS = "12,13,22";//Here searched for categories ids
        query_posts( array('category__and'=>preg_split('/[\s,]+/',$whereS)));
next you can use loop to iterate through records
if (have_posts()) : while (have_posts()) : the_post();
  /*custom code*/ 
endWhile;
Same as 'give me posts that ara linked at the same time to categories 12, 13 and 22'
that's an intersection.

Note if you want to search for posts linked to 2 or more categories ; in this case we are talking about union and not intersection, we can use simply this little code
       $whereS = "12,13,22";
        query_posts( 'cat=12,13,22');
Same as 'give me posts in the categories 12, 13 and 22'