9

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.

1 Answer 1

25

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.

3
  • 2
    Oh of course! Silly me, i spent over an hour trying to fix this. Thanks a lot!
    – qwerty
    Commented Apr 11, 2013 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
    Commented Nov 8, 2018 at 13:48
  • The documentation URL has changed. Docs for WP_Query Taxonomy Parameters are now here: developer.wordpress.org/reference/classes/wp_query/… Commented Mar 23, 2020 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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