WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

For example I have custom post type Cars and two custom taxonomies Brand (with terms BMW, Honda, etc.) and Color (Red, Green, etc.).

Car must has Brand but may not have Color.

So it may be like: Car -> Brand : BMW -> Color : Red,

and aslo it may be like this:

Car -> Brand : BMW(without color).

I need to get Cars from 1 brand which has colors: Car -> Brand : BMW -> Colors (any color). I have tryed to create query but it does not work.

$args = array(
    'post_type' => 'cars',
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'brand',
            'field' => 'slug',
            'terms' => 'bmw'
        ),
        array(
            'taxonomy' => 'color'
        )
    )
);
$query = get_posts( $args );
var_dump($query);
die();
share|improve this question
up vote 0 down vote accepted

terms parameter of tax query is required. Just pass to it all the terms for taxonomy

$args = array(
    'post_type' => 'cars',
    'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'brand',
            'field' => 'slug',
            'terms' => 'bmw'
        ),
        array(
            'taxonomy' => 'color',
            'field' => 'id',
            'terms' => get_terms('color', array('fields'=>'ids') )
        )
    )
);

Note this query will also returns 'cars' that have no brand attached, but have a color.

share|improve this answer
    
Ths for answer! But small modification - 'relation' => 'AND' – Alexander Sep 18 '13 at 10:12
    
@Alexander, I've copied 'OR' from your question. Using 'AND' cars with a brand, but without a color, will not retrieved. – gmazzap Sep 18 '13 at 10:18
    
Yes, OR was in my code. But i am trying to get Cars from BMW brand with any color and has fail with OR(this query selects cars from different Brand, not only BMW). So with AND it gets Cars only from Brand BMW and only that which has colors. Ths again! – Alexander Sep 18 '13 at 10:27

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.