問(wèn)題描述
我有一個(gè)帶有屬性顏色的產(chǎn)品.屬性值為紅色、藍(lán)色和綠色.我正在嘗試創(chuàng)建自定義搜索,但無(wú)法通過(guò)查詢(xún)提取任何產(chǎn)品.
I have a product with attribute colors. Attribute values are red, blue and green. I am trying to create a custom search but I can't get the query to pull any 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 );
我哪里做錯(cuò)了?
推薦答案
產(chǎn)品屬性顏色的正確分類(lèi)是 'pa_color'
,所以正確的工作查詢(xún)是:
The correct taxonomy for the product attribute color is 'pa_color'
, so the correct working query is:
// 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);
此代碼已經(jīng)過(guò)測(cè)試并且可以正常工作.您將獲得所有具有顏色屬性的產(chǎn)品,其值(術(shù)語(yǔ))為藍(lán)色"、紅色"和綠色"……
This code is tested and works. You will get all products that have Color attribute with the values (terms) 'blue', 'red' and 'green'…
自 WooCommerce 3 起,產(chǎn)品可見(jiàn)性由自定義分類(lèi)法 product_visibility
處理.您可以看到以下相關(guān)主題:
Since WooCommerce 3, product visibility is handled by custom taxonomy
product_visibility
. You can see the following related threads:
- woocommerce 3 中產(chǎn)品的數(shù)據(jù)庫(kù)更改
- 在 Woocommerce 的 WP_query 中獲取目錄中可見(jiàn)的產(chǎn)品
這篇關(guān)于WooCommerce 通過(guò)屬性查詢(xún)獲取產(chǎn)品的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!