按产品类型查询/筛选WooCommerce产品

8

我添加了一个新的产品类型,就像这里一样。

现在我想只显示该产品类型。这是我的查询:

$query_args = array('post_type' => 'product' );

$r = new WP_Query( $query_args );

if ( $r->have_posts() ) { .........

如何仅查询此新产品类型的产品?
2个回答

19
在WooCommerce中,"post type"是一种自定义分类法,因此您需要向WP_Query添加分类参数
$query_args = array(
   'post_type' => 'product',
   'tax_query' => array(
        array(
            'taxonomy' => 'product_type',
            'field'    => 'slug',
            'terms'    => 'your_type', 
        ),
    ),
 );

其中,terms参数与您的新产品类型类构造函数中的$this->product_type = 'your_type';部分相同。


工作完美。谢谢! - trikutin
我在产品数据中有自定义数据属性。如何在循环中使用它们?如何使用这些属性过滤产品?例如,我有颜色和尺寸数据属性。现在如何列出红色和大号的产品? - trikutin
你应该提出自己的问题。请记住,属性实际上只是分类法,因此您需要制作一个更复杂的 tax_query 语句。 - helgatheviking
我在这里问过:http://stackoverflow.com/questions/29917231/how-to-use-woocommerce-data-attributes-in-the-loop,尝试了很多组合但是没有运行成功。 - trikutin
抱歉,但只有您回答了这个问题,我仍在处理中http://stackoverflow.com/questions/30305733/filtering-with-woocommerce-data-attributes - trikutin

4
一种更简洁的方式是使用WooCommerce的wc_get_products函数而不是仅使用WP_Query。
$args = array(
    'type' => 'custom_product_type'
    );
$products = wc_get_products( $args );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接