1

I am trying to fetch products by category ID this way:

<?php

$args = array(
    'posts_per_page' => 20,
    'taxonomy' => 'product_cat',
    'post_type' => 'product',
    'post_status' => 'publish',
    'cat' => $cat_id
); 

$query = new WP_Query($args);

$posts = get_posts($args);
var_dump($posts);

?>

The $cat_id variable contains the correct category ID. I've checked it. Products are added to correct categories.

The problem is, whenever I var_dump the $posts variable I get an empty array. As soon as I remove the 'cat' keyword from the arguments I can fetch products from all categories with no problems. The only problem is the 'cat' keyword.

Am I doing something wrong?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
NakedCat
  • 852
  • 1
  • 11
  • 40

1 Answers1

1

You could try this instead:

$args = array(
    'posts_per_page' => 20,
    'post_type' => 'product',
    'post_status' => 'publish',
    'tax_query' = array(
         'taxonomy' => 'product_cat',
         'field'    => 'term_id',
         'term'     =>  $cat_id
     )
);
$query = new WP_Query($args);
var_dump($query);

I haven't test it, but it should work.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Hey, yes, I managed to test it a few minutes ago, it works (but I had to change 'id' to 'term_id'). I am selecting this answer as correct. – NakedCat Aug 01 '16 at 11:44