1

Good morning (or evening),

I try to merge in a custom archive (taxonomy-$taxonomy.php) a double (?) query. Let's try to be clear :

I’d like to display all the posts from a taxonomy. Ok, it works.

//start by fetching the terms for 'progression' taxonomy
$terms = get_terms( 'progression', array(
    'orderby'    => 'asc',
    'hide_empty' => 1
) );

And the query

// Run a query for each progression
foreach( $terms as $term ) {

     $args = array(
        'post_type' => array('my_custom_post', 'another_custom_post'),
        'progression' => $term->slug,
        );

    $query = new WP_Query( $args );

    // output the term name (here "day1", "day2"...)                
    echo $term->name;

    // Start the Loop and output the titles
       while ( $query->have_posts() ) : $query->the_post(); 
           the_title(); 
       endwhile;   

    // use reset postdata to restore original query
    wp_reset_postdata();

} ?>

(of course, I didn't find this by myself... thanks this forum !)

BUT (that’s the problem) It displays every post with this tax. However, I would like to restrict my request to another taxonomy.

A second tax 'sport' => volley, tennis, basket...

Individually, it works. BUT, as soon as I try to combine the both criterias, I fail miserably.

I could write my code (with the second query and args, but it doesn't work, so, is it usefull ?) Thanks a lot for any help.

0

You need to add a tax_query parameter with a relation to do this,

$args = array(
    'post_type' => array('my_custom_post', 'another_custom_post'),
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'progression',
            'field'    => 'slug',
            'terms'    => $term->slug,
        ),
        array(
            'taxonomy' => 'sport',
            'field'    => 'term_id',
            'terms'    => array( 1, 2, 3 ),
            'operator' => 'IN',
        ),
    ),
);
$query = new WP_Query( $args );

Of course, you'll need arrange term_id for the sport taxonomy relation.

You will find more examples and details about the taxonomy parameter in the WP_Query class reference

Hope it helps.

  • The <pre>tax_query</pre> will effectively display a list of posts with the written conditions. But... I'm trying to order my posts according to a taxonomy (in this case 'progression'). And, I found this article : wordpress.stackexchange.com/questions/14306/… ... which makes me think that I'm perhaps in a wrong direction with my taxonomies (progression). It seems to be more efficient to "play" with custom fields and get_the_meta. Or, make 3 distincts queries (for my 3 days). Thanks again !! – Cha Jan 8 '17 at 20:24
  • Yes, you can use both tax_query and meta_query in the same query. – Benoti Jan 8 '17 at 20:26

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.