2016-11-18 116 views
0

我需要獲取與某個屬性匹配的類別中的所有產品。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,因此即使存在與該類別和屬性的產品。
我該如何修改查詢?

回答

0

最後我得到的解決方案,這是你如何需要在屬性查詢:

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

注意的是,在key你需要要將pa_添加到您的屬性名稱中,並且您需要使用terms來指定屬性的值。

0

看起來你用tax_query而不是meta_querytax_query適用於taxonomie過濾器。

試試這個:

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

WP_Query#Custom_Field_Parameters

+0

我得到零結果,我敢肯定,至少有一個 –

相關問題