7

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

16

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.

  • 2
    Oh of course! Silly me, i spent over an hour trying to fix this. Thanks a lot! – qwerty Apr 11 '13 at 9:30
  • lucky you, I've spend three days on it :( Is THERE anything like some feedback how many posts are retrieved or rather WHY there are not found? Lots of tuts and examples, even here is about older version or did not work for me anyway. – piotao Nov 8 '18 at 13:48

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.