在 WP_Query 中获取 WooCommerce 订阅产品类型和特定类别

Get WooCommerce Subscription product type and specific category in a WP_Query

我正在为目录中的多个产品使用 WooCommerce 订阅插件,这些产品可作为个人产品或订阅产品使用,并且正在编写自定义模板页面来查询可作为订阅使用的产品。我的查询在下面,在我看来一切都是正确的,但由于某种原因它不起作用。谁能看出这里出了什么问题?

*请注意,如果我删除 'tax_query',所有咖啡产品都会按预期退回,但是当我尝试通过 tax_query 进行限制时,不会退回任何产品(是的,我有咖啡类别中的订阅产品)。

$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'product_cat' => 'coffee',
    'tax_query' => array( // builds the taxonomy query
            array(
                'taxonomy' => 'product_type',
                'field'    => 'name',
                'terms'    => 'subscription',
            ),
        ),
    );
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
    while ( $loop->have_posts() ) : $loop->the_post();
        wc_get_template_part( 'content', 'product' );
    endwhile;
} else {
    echo __( 'No products found' );
}
wp_reset_postdata();

您也需要为产品类别制作一个“tax_query”,以避免您这样做的问题,is deprecated since WordPress version 3.1 支持“tax_query” .所以在你的代码中:

$loop = new WP_Query( array(
    'post_type'      => 'product',
    'posts_per_page' => -1,
    'post_status'    => 'publish',
    'tax_query'      => array( // builds the taxonomy query
        'relation' => 'AND',
        array(
            'taxonomy' => 'product_cat',
            'field'    => 'slug',
            'terms'    => 'coffee',
        ),
        array(
            'taxonomy' => 'product_type',
            'field'    => 'name',
            'terms'    => 'subscription',
        ) 
    )
) );

if ( $loop->have_posts() ) {
    while ( $loop->have_posts() ) : $loop->the_post();
        wc_get_template_part( 'content', 'product' );
    endwhile;
} else {
    echo __( 'No products found' );
}

wp_reset_postdata();

应该可以。