【问题标题】:Get WooCommerce Subscription product type and specific category in a WP_Query在 WP_Query 中获取 WooCommerce 订阅产品类型和特定类别
【发布时间】:2021-02-09 02:33:17
【问题描述】:

我正在为目录中的多个产品使用 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();

【问题讨论】:

    标签: php wordpress woocommerce product woocommerce-subscriptions


    【解决方案1】:

    您还需要为产品类别创建一个“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();
    

    它应该可以工作。

    【讨论】:

    • 像 LoicTheAztec 一样工作,非常感谢!而且还让我直接了解折旧的位,这非常有帮助。
    猜你喜欢
    • 2017-12-03
    • 2021-11-07
    • 1970-01-01
    • 2019-01-26
    • 2018-02-25
    • 2018-12-19
    • 1970-01-01
    • 2018-08-26
    • 2018-05-17
    相关资源
    最近更新 更多