Problem with get_posts, tax_query and counting the number of posts

I want to count the number of posts that has simoultaneously 3 different taxonomies. THe code i’m using is this:

$products = get_posts(array(
    'post_type' => 'products',
    'posts_per_page' => -1,
    'post_status' => 'publish',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'collection',
            'field' => 'slug',
            'terms' => array($current_collection),
            'operator' => 'IN'
        ),
        array(
            'taxonomy' => 'type',
            'field' => 'slug',
            'terms' => array($current_type),
            'operator' => 'IN'
        ),
        array(
            'taxonomy' => 'color',
            'field' => 'slug',
            'terms' => array($current_type),
            'operator' => 'IN'
        )
    )   
));
$countpost = count($products);

The problem occours when the colors and type taxonomy term I’m looking for do not exists…

Read More
  • if the collection does not exists, the count is 0

  • if the type does not exists, it returns posts with the specified collection and color

  • it the color does not exists, it returns posts with the specified collection and type

what I was expenting, since the relation is AND, was that if one of the terms does not exists, the count should be always 0, instead of basically ignoring that term and considering only tho other two…

am I doing something wrong? how can I fix it?

thanks a lot!

Related posts

Leave a Reply

1 comment

  1. Try this again removing operator and relation arguments as follows: here is a useful link http://ottopress.com/2010/wordpress-3-1-advanced-taxonomy-queries/

    $products = get_posts(array(
        'post_type' => 'products',
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'tax_query' => array(
            array(
                'taxonomy' => 'collection',
                'field' => 'slug',
                'terms' => array($current_collection)
            ),
            array(
                'taxonomy' => 'type',
                'field' => 'slug',
                'terms' => array($current_type)
            ),
            array(
                'taxonomy' => 'color',
                'field' => 'slug',
                'terms' => array($current_type)
            )
        )   
    ));
    $countpost = count($products);