WP_query taxonomy + get all posts with two terms from same taxonomy

This is a follow up question to Add_query_arg + two times the same argument?

I want to get the post count from all posts tagged with 2 different tags from same taxonomy

$args2 = array(
    'post_type' => 'custom',
    'tax_query' => array( 'relation' => 'AND' )
);
$args['tax_query'][0] = array( 
    'taxonomy' => 'events',
    'field' => 'slug',
    'terms' => 'tag1' 
);
$args['tax_query'][1] = array(
    'taxonomy' => 'events',
    'field' => 'slug',
    'terms' => 'tag-2' 
);
$query = new WP_Query($args);
echo $query->post_count;

With this code I only get the post_count for one of these tags. How i do get both?
I couldn’t find an answer at WordPress codex.

Help is much appreciated.

1 Answer
1

You don’t need to 2 array for tax query. You can try this scenario:

$args2 = array('post_type' => 'custom',
               'tax_query' => array( 
                                array( 'taxonomy' => 'events', 
                                        'field' => 'slug',
                                        'terms' => array( 'tag1', 'tag-2')
                                      )
                                    )
                );
$query = new WP_Query($args);
echo $query->post_count;

You can see the Codex for better understanding.

Leave a Comment