WordPress 按分类法获取产品

WordPress get product by taxonomy

我在 'membership-level' 类别下创建了 7 个 WooCommerce 产品。现在,为了获得这些产品,我使用了以下代码但没有按预期工作。

$args = [
    'post_type' => 'product',
    'tax_query' => array(
        array(
            'taxonomy' => 'membership-level',
        )
    )
];

echo '<pre>';
print_r( get_posts( $args ) );
echo '</pre>';

有什么我遗漏的吗?

要按产品类别查询产品你必须设置

  • 分类名称:在你的例子中是“product_cat”
  • field (p.ex: term_id, slug): 在你的例子中是 slug
  • 和学期

所以尝试类似的东西


$args = [
    'post_type' => 'product',
    'tax_query' => array(

            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array('membership-level')

    )
];

echo '<pre>';
print_r( get_posts( $args ) );
echo '</pre>';