1

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); ?>
0

Please let me know if this examples help you figure things out:

  • Thanks for the link, it sounds promising but can't seem to get it to work. Can you spot anything obvious I'm doing wrong here? <?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); ?> – Monk Mar 17 '17 at 2:57
0

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.

0

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; `

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.