I'd like to craft a query to return posts based on the conditional presence of certain tags. The pseudo query is: return posts with "((tagA OR tagB) AND (tagX OR tagY))". But I'm having issues crafting such a query in WP_Query and would like any suggestions.

From https://codex.wordpress.org/Class_Reference/WP_Query#Tag_Parameters I know this will display posts that have either of these tags:
$query = new WP_Query( array('tag'=>'tagA,tagB'));

and this that has all of these tags:
$query = new WP_Query( array('tag'=>'tagX+tagY'));

but I have two OR queries joined with an AND and . I tried this:
$query = new WP_Query( array('tag'=>'tagA,tagB+tagX,tagY'));

but this did not work.
Can I use WP_Query to do such a search? Any suggestions appreciated.


"Gary D" pointed me in the right direction and "Rarst" yes you can use this on the same taxonomy. This query below gives the expected result in WP4.5.2 and I'm using standard tags on standard posts:

$args = array( /* Return posts with ((tagA OR tagB) AND (tagX or tagY)) */ 'meta_key' => 'SortField', 'order' => 'DESC', 'orderby' => 'meta_value', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'post_tag', 'field'=>'slug', 'terms'=> array('tagA','tagB'), 'operator'=>'IN' ), array( 'taxonomy' => 'post_tag', 'field'=>'slug', 'terms'=> array('tagX','tagY'), 'operator'=>'IN' ), ) ); $query = new WP_Query($args); if ( $query->have_posts() ) : while ($query->have_posts() ) : $query->the_post();


Give something like this a try: (it came from the same page you linked to, just scroll down a bit more).

$args = array(
  'post_type' => 'post',
  'tax_query' => array(
    'relation' => 'AND', // searches for posts meeting both conditions
      'taxonomy' => 'midgets',
      'field'    => 'slug',
      'terms'    => array( 'tagA,TagB' ), // searches for EITHER tag
      'taxonomy' => 'donkeys',
      'field'    => 'slug',
      'terms'    => array( 'tagX,TagY' ), // searches for EITHER tag
$query = new WP_Query( $args );
  • Are you certain that this will work across same taxonomy? Just thinking aloud, I wouldn't be sure...
    – Rarst
    May 25 '16 at 16:38
  • See my UPDATE in initial question for the answer
    – John
    May 26 '16 at 2:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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