首页 文章

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

提问于
浏览
0

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

这是我的代码:

$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

    它看起来你使用 tax_query 而不是 meta_query . tax_query 用于分类过滤器 .

    试试这个:

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

    WP_Query#Custom_Field_Parameters

  • 0

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

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

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

相关问题