WooCommerce通过属性查询获取产品

时间:2017-08-23 00:06:20

标签: php wordpress woocommerce attributes product

我有一个带属性颜色的产品。属性值为红色,蓝色和绿色。我正在尝试创建自定义搜索,但我无法通过查询来提取任何产品。

$args =  array(
    'post_type'      => array('product'),
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query'     => array( 
        array(
            'key' => '_visibility',
            'value' => array('catalog', 'visible'),
            'compare' => 'IN',  
        ) 
    ),
    'tax_query'      => array( 
        array(
            'taxonomy'        => 'product',
            'field'           => 'slug',
            'terms'           =>  array('blue', 'red', 'green'),
            'operator'        => 'IN',
        ),
    )
);

$products = new WP_Query( $args );

我哪里出错了?

1 个答案:

答案 0 :(得分:6)

产品属性颜色的正确分类是 'pa_color' ,因此正确的工作查询是:

// The query
$products = new WP_Query( array(
   'post_type'      => array('product'),
   'post_status'    => 'publish',
   'posts_per_page' => -1,
   'meta_query'     => array( array(
        'key' => '_visibility',
        'value' => array('catalog', 'visible'),
        'compare' => 'IN',
    ) ),
   'tax_query'      => array( array(
        'taxonomy'        => 'pa_color',
        'field'           => 'slug',
        'terms'           =>  array('blue', 'red', 'green'),
        'operator'        => 'IN',
    ) )
) );

// The Loop
if ( $products->have_posts() ): while ( $products->have_posts() ):
    $products->the_post();
    $product_ids[] = $products->post->ID;
endwhile;
    wp_reset_postdata();
endif;

// TEST: Output the Products IDs
print_r($product_ids);

此代码已经过测试并且有效。您将获得具有Color属性的所有产品,其值(条款)为'blue','red'和'green'......