Query for posts in 2 taxonomies

I am currently using the following code to display a list with links to posts in a specific CPT and taxonomy:

  <?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;
     }
} ?>

It’s working fine like it should, however I want to only display posts that is in both my taxonomies. What do I have to add to do so?

Read More

Any help is appreciated, thanks.

Related posts

Leave a Reply

2 comments

  1. According to the Codex, here’s how you would query posts from several 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
        )
    )
    
  2. Ok I figured it out!

    <?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;
         }
    }
    } ?>