tax_query in get_posts() not working?

I’m trying to print out all the posts within every taxonomy for a custom post type called product (jigoshop products). So i get all of the taxonomies using $cats = get_terms('product_cat');, then i loop through them all, and get all the posts that is within the taxonomy. The problem is, it doesn’t work. It just returns blank!

$uposts = get_posts(array(
    'post_type' => 'product',
    'numberposts' => -1,
    'tax_query' => array(
        'taxonomy' => $cat->taxonomy,
        'field' => 'slug',
        'terms' => array($cat->slug),
        'operator' => 'IN'
    )
));

If i change the 'terms' => array($cat->slug) to 'terms' => $cat->slug it returns all posts, as if it ignores the tax_query completely.

Read More

Any ideas what’s causing this to fail? I’ve tried playing around with operator, changing field to ID (and also sending $cat->ID as a term)… nothing works!

$cat has the following values:

stdClass Object
(
    [term_id] => 114
    [name] => Ny testkategori
    [slug] => ny-testkategori
    [term_group] => 0
    [term_taxonomy_id] => 115
    [taxonomy] => product_cat
    [description] => 
    [parent] => 0
    [count] => 2
    [meta_id] => 3
    [jigoshop_term_id] => 114
    [meta_key] => order
    [meta_value] => 1
)

So $cat->slug and $cat->taxonomy are valid values.

Related posts

Leave a Reply

1 comment

  1. The tax_query takes an array of tax query argument arrays (it takes an array of arrays) but you are using only a single array. The correct code is as follows.

    $uposts = get_posts(
        array(
            'post_type' => 'product',
            'numberposts' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => $cat->taxonomy,
                    'field' => 'slug',
                    'terms' => array($cat->slug),
                    'operator' => 'IN',
                )
             )
        )
    );
    

    For more information visit this page.