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

时间:2016-07-31 15:31:57

标签: php wordpress woocommerce categories product

我正在尝试按类别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'关键字。

我做错了吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试这样做:

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

我还没有对它进行测试,但它应该有效。

相关问题