問題描述
我有一個帶有屬性顏色的產品.屬性值為紅色、藍色和綠色.我正在嘗試創建自定義搜索,但無法通過查詢提取任何產品.
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 );
我哪里做錯了?
推薦答案
產品屬性顏色的正確分類是 'pa_color'
,所以正確的工作查詢是:
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);
此代碼已經過測試并且可以正常工作.您將獲得所有具有顏色屬性的產品,其值(術語)為藍色"、紅色"和綠色"……
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 起,產品可見性由自定義分類法 product_visibility
處理.您可以看到以下相關主題:
Since WooCommerce 3, product visibility is handled by custom taxonomy
product_visibility
. You can see the following related threads:
- woocommerce 3 中產品的數據庫更改
- 在 Woocommerce 的 WP_query 中獲取目錄中可見的產品
這篇關于WooCommerce 通過屬性查詢獲取產品的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!