我无法按类别 ID 获取 WooCommerce 产品

I can't fetch WooCommerce products by category id

我正在尝试通过这种方式按类别 ID 获取产品:

<?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);

?>

$cat_id 变量包含正确的类别 ID。我检查过了。产品已添加到正确的类别。

问题是,每当我 var_dump $posts 变量时,我得到一个空数组。一旦我从参数中删除 'cat' 关键字,我就可以毫无问题地从所有类别中获取产品。唯一的问题是 'cat' 关键字。

我是不是做错了什么?

您可以试试这个:

$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);

我还没有测试过,但应该可以。