問題描述
這有點奇怪,但我很難找到如何做到這一點的答案:
This is a bit of an odd one, but I'm having trouble finding an answer for how to do this:
我正在嘗試創(chuàng)建一個自定義查詢,以獲取 WooCommerce 訂單中包含的所有產品(及其元數據).
I'm attempting to create a custom query that gets all the products (and their meta) which are contained within a WooCommerce order.
例如,假設我有這些訂單待處理:
For example, let's say I have these orders pending:
- 產品 1
- 產品 2
- 產品 3
- 產品 4
- 產品 5
- 產品 6
我的目標是根據這些訂購的產品創(chuàng)建一個列表,該列表按產品的元進行排序.像這樣:
My goal is to create a list based off these ordered products, which is ordered by the product's meta. Something like this:
- 產品 1
- 產品 3
- 產品 4
但同樣,這些只能是訂單中的產品(包括數量).
But again, these would only be products (including their quantities) that sit within an order.
我面臨的問題是訂購商品"和訂單項元"存儲在數據庫中的數據非常有限,并且不會顯示與產品相關的所有信息.因此,換句話說,我沒有找到一種方法來獲取創(chuàng)建循環(huán)以創(chuàng)建我的列表所需的信息.
The problem I'm facing is that "Order Items" and "Order Item Meta" as stored in the database are quite limiting and do not display all the information associated with a product. So in other words, I'm not finding a way to get to the info I need to create the loop to create my list.
我的數據庫技能有限,因此不勝感激!
My DB skills are limited so ideas would be appreciated!
推薦答案
以下是一些可能對您有所幫助的相關代碼:
Here is some related code that might help you:
add_filter( 'woocommerce_shop_order_search_fields', 'woocommerce_shop_order_search_product_cat' );
function woocommerce_shop_order_search_product_cat( $search_fields ) {
$args = array(
'post_type' => 'shop_order'
);
$orders = new WP_Query($args);
if($orders->have_posts()) {
while($orders->have_posts()) {
$post = $orders->the_post();
$order_id = get_the_ID();
$order = new WC_Order($order_id);
$items = $order->get_items();
foreach($items as $item) {
$product_cats = wp_get_post_terms( $item['product_id'], 'product_cat' );
foreach($product_cats as $product_cat) {
add_post_meta($order_id, "_product_cat", $product_cat->name);
}
}
}
};
$search_fields[] = '_product_cat';
return $search_fields;
}
這篇關于WooCommerce 按產品元查詢訂單項的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!