I was wondering how to solve this issue.

This is my Query:

$query = new WP_Query( array( 
   'posts_per_page' => 6,
    'orderby' => 'date', 
    'order' => 'DESC', 
    'category__not_in' => array( 7, 22 ) ) );

This is a simple query, What it does is queries all the recent posts and excludes the posts having category IDs 7 and 22.

I have some posts which have two categories linked to it, like, "7 and 10" and "22 and 13". above query excludes these posts too (as it should be), but I also want the query to INCLUDE posts that have two or more categories - one of which might be 7 or 22. I was wondering is it possible?

I hope I've explained it. I appreciate any help on this.

1 Answer 1


I don't think you can express logic like this in query arguments and custom SQL will probably be nightmarish.

I would try to flip the logic. Declare category__in to be list of all categories, but the ones you don't want.

You can build such list by code, like:

'category__in' => get_categories( array( 'fields' => 'ids', 'exclude' => '7,22' ) ),

PS I am not sure about performance aspect of such query, depends on number of categories involved I guess. Test before using in production.

  • using category__in requires editing the code manually every time I create a new category. So best way is to write custom SQL query? Jul 25, 2013 at 23:03
  • @WebWarrior why manually? you could build such list by code. I wouldn't even know where to start on SQL, "not this unless that" would be challenging as above
    – Rarst
    Jul 25, 2013 at 23:19
  • how do I list categories such that ? I appreciate your help on this. Thanks Jul 26, 2013 at 16:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.