web-dev-qa-db-fra.com

Requête pour les posts dans 2 taxonomies

J'utilise actuellement le code suivant pour afficher une liste avec des liens vers des publications dans une taxonomie et un CPT spécifiques:

  <?php
$custom_terms = get_terms('videoscategory');

foreach(array($custom_terms as $custom_term) {
    wp_reset_query();
    $args = array('post_type' => 'product',
        'tax_query' => array(
      'relation' => 'AND',
    array(
        'taxonomy' => 'videoscategory',
        'field' => 'slug',
        'terms' => $custom_term->slug
    ),
    array(
        'taxonomy' => 'product_category',
        'field' => 'slug',
        'terms' => $other_custom_term->slug
    ),

)

     );

     $loop = new WP_Query($args);
     if($loop->have_posts()) {
        echo '<h1 style="margin-top:10px;">'.$custom_term->name.'</h1>';

        while($loop->have_posts()) : $loop->the_post();
            echo '<h2><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
        endwhile;
     }
} ?>

Cela fonctionne bien comme il se doit, mais je souhaite uniquement afficher les publications qui se trouvent dans mes deux taxonomies. Que dois-je ajouter pour le faire?

Toute aide est appréciée, merci.

2
Rich

Ok je l'ai compris!

<?php
$custom_terms = get_terms('your_other_category');
$other_custom_terms = get_terms('your_category');

foreach ($custom_terms as $custom_term) {
foreach ($other_custom_terms as $other_custom_term) {
    wp_reset_query();
    $args = array('post_type' => 'product',
        'tax_query' => array(
  'relation' => 'AND',
    array(
        'taxonomy' => 'your_category',
        'field' => 'slug',
        'terms' => $other_custom_term->slug
    ),
            array(
                'taxonomy' => 'your_other_category',
                'field' => 'slug',
                'terms' => $custom_term->slug,
            ),
        ),
     );

     $loop = new WP_Query($args);
     if($loop->have_posts()) {
        echo '<h1 style="margin-top:10px;">'.$custom_term->name.'</h1>';

        while($loop->have_posts()) : $loop->the_post();
            echo '<h2><a href="'.get_permalink().'">'.get_the_title().'</a></h2>';
        endwhile;
     }
}
} ?>
1
Rich

Selon le Codex , voici comment interroger les publications de plusieurs taxonomies:

'tax_query' => array(
    'relation' => 'AND',
    array(
        'taxonomy' => 'videoscategory',
        'field' => 'slug',
        'terms' => $custom_term->slug
    ),
    array(
        'taxonomy' => 'yourothertaxonomy',
        'field' => 'slug',
        'terms' => $other_custom_term->slug
    )
)
3
montrealist