I have the following code to obtain products within a category

 $product = new WC_Product($id);

 $categories = $product->get_category_ids(); //return array(21)

 $args = array();

 $args["posts_per_page"] = 10;

 $args["post_type"] = "product";

 $args["post_status"] = "publish";

 $args["category__in"] = $categories;

 $myposts = get_posts($args);

And get_posts return empty when I know there are 5 products in this category


You can achieve that using the tax_query, see the example in the code below:

$args = array(
  'posts_per_page' => 10,
  'post_type' => 'product',
  'post_status' => 'publish',
  'tax_query' => array(
     'taxonomy' => 'the_taxonomy_slug', //the slug of the taxonomy you want to get
     'field' => 'term_id',
     'terms' => $categories

See reference in the Codex

  • in terms i put the ids of category o the names? – Miguel Ruiz Bas Jul 18 '17 at 6:36
  • You choose, if you if you see the field key is set to search for the term_id, you can also search for the slug just change the 'field' => 'term_id' to 'field' => 'slug' and in 'terms' you pass the slug of your categories – Cesar Henrique Damascena Jul 18 '17 at 11:34
  • and the 'the_taxonomy_slug' should be category. right? thanksss!! – Miguel Ruiz Bas Jul 18 '17 at 12:03
  • Yep, the_taxonomy_slug is the slug of your taxonomy, in your case is category – Cesar Henrique Damascena Jul 18 '17 at 12:24

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.