Question

i have "Tag1" and "Tag2" i want to find most recent post with both tags.So far i have tried this, i know im close, but it is listing all posts containing either tag.

$args = array(
        'relation' => 'AND',
        array(
            'taxonomy'         => 'post_tag',
            'terms'            => 'agirt',
            'field'            => 'slug',
            'operator'         => 'AND'.
        ),
        array(
            'taxonomy'         => 'post_tag',
            'terms'            => 'fetch',
            'field'            => 'slug',
        ),
    );
    $the_query = new WP_Query($args);
    if ( $the_query->have_posts() ) {
        $html = '<ul>';
        while ( $the_query->have_posts() ) {
            $the_query->the_post();
            $post_title = $the_query->post->post_title; 
            echo "<li>$post_title</li>";
        }
        $html .= '</ul>';
        echo $html;
    }
Was it helpful?

Solution

Using the tax_query param in your args (and replacing the dot with a comma) should get you what you're looking for:

$args = array(
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'slug',
            'terms'    => 'fetch',
        ),
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'slug',
            'terms'    => 'agirt',
        )
    )
);
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top