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.

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
    tax_query in get_posts() not working? => 
    [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.

1
1

tax_query takes an array of tax query arguments arrays (it takes an array of arrays) but you are using only single array. The correct code is as following.

$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.

Leave a Comment