Filter custom posts by multiple taxonomies

Im working with custom post types - named 'Products'

I have multiple taxonomies registered - 'Category' and 'Dosage'

And I'm trying to setup pages that only display custom post types 'products' IF taxonomy Category='injectors' AND Dosage='1ml, 2ml, 5ml'

I hope that makes sense - manage to get custom post archives working fine for a single taxonomy, but not sure about filtering by multiple.

Cheers,

This is the code i'm trying to get work but it doesn't

?php 
$myquery['tax_query'] = array( 
   'relation' = 'OR', 
    array( 
         'taxonomy' = 'product_category',
         'terms' = array('shrouded'),
         'field' = 'slug', 
    ), 
    array( 
        'taxonomy' = 'dosages',
        'terms' = array( '1ml' ),
        'field' = 'slug', 
   ),
);
query_posts($myquery); ?

Topic multi-taxonomy-query custom-post-types Wordpress

Category Web


This should not be using query_posts, for that matter nothing should ever be using query_posts as there are better ways to modify the main query before execution. See pre_get_posts

That said, based on the use case this should be handled with an additional custom query, not a modification to the main query.

Also the question cites the need for an AND relationship between the 2 taxonomies, but then uses OR in the code example.

Solution:

$args = array(
   'post_type' => 'products',
   'posts_per_page' => -1, //<-- Get all
   'tax_query' = array( 
      'relation' => 'AND', 
      array( 
         'taxonomy' => 'product_category',
         'terms' => array('injectors'),
         'field' => 'slug', 
      ), 
      array( 
        'taxonomy' => 'dosages',
        'terms' => array( '1ml','2ml','5ml' ),
        'field' => 'slug'
      )
   )
);
$products = new WP_Query($args);
if($products->have_posts()) : while($products->have_posts()) : the_post() ;
   // Output desired markup inside custom query loop here.
endwhile; endif; `

Since you're using query_posts, you're overriding the whole archive query, so you have to specify your custom post type in your query parameters, like so:

$myquery['post_type'] = 'products';

However, the better solution would be to avoid query_posts altogether, so the main query doesn't get broken, and use one of the other approaches as described in the answer here.


About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.