I want to get a list of products of a given category from WP_query, but it won't work like it should.
I've done this :
$args = array(
'post_type' => 'product',
'product_cat' => 17,
);
$products = new WP_Query($args);
But this returns every product from my shop ... I have also tried with 'cat', 'category' and 'category_name' attr with same result.
I've tried using tax_query :
$args = array(
'post_type' => 'product',
'tax_query' => array(
'taxonomy' => 'product_cat',
'terms' => 17
),
);
$products = new WP_Query($args);
And this also returns every products I have also tried with 'cat', 'category' and 'category_name' with same result.
I have managed using the following code to get regular posts from a given category.
$args = array(
'post_type' => 'post',
'cat' => 22
);
$posts = new WP_Query($args);
A couple more things :
- I am certain I have the right category id.
- tax_query worked for the posts too
edit :
tax_query
returns every products, ignoring myproduct_cat
attrI have been looking to do this for days and tried every possible solution of similar questions on stack and other sites without success... Why doesn't it work for products ?
EDIT : the code snipet with tax_query
was wrong so I changed it.
EDIT 2 : I have tried several new Things, here is the summary :
- disabled all custom hooks : same results
- instantiated a
WC_Product
manually by the id of an actual product as an argument. It shows that itscategory_ids
attribute is empty, even though the product does have a category on the admin panel... and the category taxonomy page shows the right stuff too. - when I do
var_dump(get_the_terms($postID, 'category'));
on a regular post it works fine
EDIT 3 :
- disabled all plugins but Woocommerce with same result...
- when I do var_dump(get_post_types());
, the product post type does not show. And so naturally, when I do var_dump(get_object_taxonomies('product'));
, it returns an empty array.
'cat'
,'category'
,'category_name'
, and'product_cat'
won't work as arguments because product categories are a separate taxonomy to categories, and you need atax_query
to query custom taxonomies. There is nothing wrong with the code for the tax query I can see here. Either the ID actually is wrong, orproduct
andproduct_cat
aren't the right names for the post type and taxonomy. They would be if you're using WooCommerce. Are you?pre_get_posts
hook anywhere in such a way that could interfere with this query.'suppress_filters' => false
? Just an idea from the top of my head. Don't know if there any filters in place to suppress since you haven't mentioned what you use for the products.'suppress_filters
does not change anythingproduct_cat
is correct for WooCommerce. Is this the actual code you’re using? Or an example? And issue could exist isn’t he actual code that’s not present in this example, because this code is fine.