繁体   English   中英

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

[英]Filter WooCommerce products by taxonomy terms and custom fields in a WP_Query

在 WooCommerce 中,我有一个产品类别boots-2 (术语 slug),其中包含 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();

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

我错过了什么?

第一个 Woocommerce 产品类别是一个自定义分类法,与 WordPress 类别无关。 现在,对于WP_Query 和分类参数,最好使用以下税务查询:

$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 - 分类参数部分文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM