2014-01-14 106 views
7

這是一個驅使我堅果..我試圖查詢和輸出基於特定屬性的WooCommerce產品。例如,我設置了一個名爲on的屬性,可能的值爲yesno基於屬性查詢WooCommerce產品

我查詢中使用下列內容:

$args = array( 
    'post_type' => 'product', 
    'meta_key' => 'pa_on', 
    'meta_value' => 'yes', 
    'posts_per_page' => -1 
); 

query_posts($args); 

meta_key也許是至關重要的;如果我叫它on我什麼也沒得到。如果我將它稱爲pa_on(因爲這是我理解WooCommerce自定義屬性的構造方式),我什麼也得不到。

但是,如果我嘗試不同的查詢並使用_featured這是一個標準的WooCommerce自定義元件,它會返回相關的精選帖子。幫助,任何人?

+0

似乎超出了StackOverflow的範圍。這不是一個明確的PHP問題。這是特定於WordPress,因此,該職位應遷移到wordpress.stackexchange.com – Chris

+0

謝謝克里斯 - 我會讓它掛起,如果主持人移動線程,所以它:) –

回答

0

猜你需要的是與meta_query值設置查詢:

$args = array(
'post_type' => 'product', 
'meta_query' => array(
    array(
     'key' => 'pa_on', 
     'value' => 'yes', 
     'compare' => '=' 
    ) 
) 
); 
$query = new WP_Query($args); 

您可以瞭解到更多關於在這裏:​​ http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

+1

謝謝Kriesi,但我害怕這也行不通:我通常使用這種格式進行查詢,並且已經嘗試過 - 你會認爲這可以在任何主題的任何地方工作,對吧?!我顯然是以錯誤的方式看待WooCommerce屬性 - 這裏有什麼不對.. –

+0

你知道如何用sql查詢原始數據嗎? – huykon225

6

我知道這是一個古老的一個,但以防萬一有人像我今天所做的那樣絆倒它 - Woocommerce(我正在使用v2.6.2)似乎將這些自定義屬性存儲爲分類法。

我懷疑原始問題的正確ARGS是這樣的:

​​

使用適當的值,我安裝的,它解決了我的問題。

3

對於新woocommerce使用:

$attribute = 'on'; 
$value = 'yes'; 
$args = array(
    'post_type' => 'product', 
    'tax_query' => array(
    array(
     'taxonomy'  => 'pa_' . $attribute, 
     'terms'   => $value, 
     'field'   => 'slug', 
     'operator'  => 'IN' 
     ) 
    ) 
); 
0

如果產品屬性被保存爲特定的產品屬性(即不是全球性),那麼你就不能查詢它的分類,而不是您可以使用此代碼段(從複製http://snippet.fm/snippets/query-woocommerce-products-product-specific-custom-attribute/):

// Set custom attribute name and value to search for 
$attribute_name = 'color'; 
$attribute_value = 'green'; 

$serialized_value = serialize('name') . serialize($attribute_name) . serialize('value') . serialize($attribute_value); // extended version: $serialized_value = serialize($attribute_name) . 'a:6:{' . serialize('name') . serialize($attribute_name) . serialize('value') . serialize($attribute_value) . serialize('position'); 
$args = array(
    'post_type'  => 'product', 
    'post_status' => 'any', 
    'posts_per_page' => -1, 
    'orderby'  => 'title', 
    'order'   => 'ASC', 
    'meta_query' => array(
     array(
      'key'  => '_product_attributes', 
      'value' => $serialized_value, 
      'compare' => 'LIKE', 
     ), 
    ), 
); 
$loop = new WP_Query($args); 
while ($loop->have_posts()) { 
    $loop->the_post(); 
    // do stuff here... e.g. get_the_ID() 
} 
wp_reset_postdata();