Woocommerce - 获取具有特定属性的产品类别

时间:2016-11-18 12:30:45

标签: wordpress woocommerce

我需要将所有产品都放在与属性匹配的类别中。

这是我的代码:

$title     = isset($instance['title']) ? $instance['title'] : '';
$car_type  = isset($instance['cartype']) ? $instance['cartype'] : 'usato';
$car_brand = isset($instance['carbrand']) ? $instance['carbrand'] : '';
$limit     = isset($instance['limit']) ? $instance['limit'] : null;
$order     = $instance['order'];
$carousel  = $instance['carousel'];


$query_args = [
    'post_type'   => 'product',
    'post_status' => 'publish',
    'product_cat' => $car_type                
 ];

 // Ordino i risultati
 if ($order == 'random') {
     $query_args['orderby'] = 'random';
 } else {
     $query_args['orderby'] = 'name';
     $query_args['order']   = $order;
 }

 // Devo limitare il numero di risultati?
 if ($limit) {
     $query_args['posts_per_page'] = $limit;
 }

 if ($car_brand != '') {
     $query_args['tax_query'] = array(
         array(
             'key'     => 'pa_marca',
             'value'   => 'nike',
             'field'   => 'slug',
             'compare' => '='
         )
     );
 }

问题是,即使有一个具有该类别和该属性的产品,我总是得到0结果 我该如何修改查询?

2 个答案:

答案 0 :(得分:0)

您看起来使用tax_query代替meta_querytax_query用于分类过滤器。

试试这个:

$query_args['meta_query'] => array(
    array(
        'key'     => 'pa_marca',
        'value'   => 'nike',
        'compare' => '=',
    ),      
);

WP_Query#Custom_Field_Parameters

答案 1 :(得分:0)

最后我得到了解决方案,这就是你需要查询属性的方法:

$query_args['tax_query'] = array(
    array(
        'key'     => 'pa_brand',
        'field'   => 'slug',
        'terms'   => 'nike'
    )
);

请注意,在key中,您需要在属性名称中添加pa_,并且需要使用terms来指定属性的值。

相关问题