通过分类术语和WP_Query中的自定义字段过滤WooCommerce产品

问题描述

在WooCommerce中,我有一个产品类别boots-2 (词条),其中包含350种产品。

我需要返回该类别中所有具有元密钥_translate_lock和元值 1 的产品,如以下WP_Query所定义:

这是我的代码

$args = array(
        'posts_per_page' => '400','category' => 'boots-2','post_type'  => 'product','orderby' => 'name','meta_query' => array(
            array(
            'key' => '_translate_lock','value' => '1','compare' => '='
            )
        ),);

    $query  = new  WP_Query($args);


    if ( $query->have_posts() ) {

        while ( $query->have_posts() ) {

            $query->the_post();

            $productId = get_the_ID() ;
            println("retrieved product id is $productId");
            
        }
    } 
    wp_reset_query();

此代码返回的产品不属于子类别boots-2的类别,我尝试将查询字符串更改为cat=881,其中881是类别,但代码仍会返回其他类别的产品。

我想念什么?

解决方法

第一个Woocommerce产品类别是与WordPress类别无关的自定义分类法。现在,对于WP_Query and taxonomy parameters,最好使用以下税收查询:

$query = new WP_Query( array(
    'posts_per_page' => -1,'post_type'      => 'product','post_status'    => 'publish','orderby'        => 'name','order'          => 'ASC','meta_query'     => array(
        array(
            'key'       => '_translate_lock','value'     => '1',// 'compare'    => '=' // not needed as default value is '='
        )
    ),'tax_query' => array(
        array(
            'taxonomy'  => 'product_cat',// Woocommerce product category taxonomy
            'field'     => 'slug',// can be: 'name','slug' or 'term_id'
            'terms'     => array('boots-2'),)
    ),) );

$results = []; // Initializing

if ( $query->have_posts() ) :
    while ( $query->have_posts() ) : $query->the_post();
        $product_id   = get_the_ID();
        $product_name = get_the_title();

        $results[] = $product_name .' ('.$product_id.')'; 
    endwhile;
    wp_reset_postdata();

    // Displaying results
    printf( '<p><strong>Retrieved products are</strong>:<br> %s<p>',implode(',<br>',$results) ); 
else :
    echo '<p>No results found.</p>';
endif;
wp_reset_query();

经过测试可以正常工作。

请参见WP_Query - taxonomy-parameters section documentation

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...