問題描述
我正在嘗試使用以下方法從 Woocommerce 的訂單中提取項目元值:
I'm trying to extract item meta value from Woocommerce's orders by using:
$data = wc_get_order_item_meta( $item, '_tmcartepo_data', true );
但是,我找不到獲取 order_item_id 作為第一個參數(shù)的方法(使用 get_items)
However, I can't find a way to get order_item_id as the first parameter (using get_items)
global $woocommerce, $post, $wpdb;
$order = new WC_Order($post->ID);
$items = $order->get_items();
foreach ( $items as $item ) {
$item_id = $item['order_item_id']; //???
$data = wc_get_order_item_meta( $item_id, '_tmcartepo_data', true );
$a = $data[0]['value'];
$b = $data[1]['value'];
echo $a;
echo $b;
}
我的意思是這個訂單 item_id (1 和 2)
And I mean this order item_id (1 and 2)
數(shù)據(jù)庫中的Order_item_id - 圖片
我該怎么做?
謝謝.
推薦答案
2018 年更新:
- 用兩種可能的情況澄清答案
- 添加了對 woocommerce 3+ 的兼容性
所以可能有兩種情況:
1) 獲取商品元數(shù)據(jù)(不在訂單商品元數(shù)據(jù)中設(shè)置):
1) Get product meta data (not set in order item meta data):
您將需要在 foreach 循環(huán)中為 WC_Order
獲取產(chǎn)品 ID,并為該產(chǎn)品獲取一些元數(shù)據(jù),您將使用 get_post_meta()
函數(shù) ( 但不是 wc_get_order_item_meta()
).
You will need to get the product ID in the foreach loop for a WC_Order
and to get some metadata for this product you wil use get_post_meta()
function ( but NOT wc_get_order_item_meta()
).
這是您的代碼:
global $post;
$order = wc_get_order( $post->ID );
$items = $order->get_items();
foreach ( $order->get_items() => $item ) {
// Compatibility for woocommerce 3+
$product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $item['product_id'] : $item->get_product_id();
// Here you get your data
$custom_field = get_post_meta( $product_id, '_tmcartepo_data', true);
// To test data output (uncomment the line below)
// print_r($custom_field);
// If it is an array of values
if( is_array( $custom_field ) ){
echo implode( '<br>', $custom_field ); // one value displayed by line
}
// just one value (a string)
else {
echo $custom_field;
}
}
<小時>
2) 獲取訂單項元數(shù)據(jù)(自定義字段值):
global $post;
$order = wc_get_order( $post->ID );
$items = $order->get_items();
foreach ( $order->get_items() as $item_id => $item ) {
// Here you get your data
$custom_field = wc_get_order_item_meta( $item_id, '_tmcartepo_data', true );
// To test data output (uncomment the line below)
// print_r($custom_field);
// If it is an array of values
if( is_array( $custom_field ) ){
echo implode( '<br>', $custom_field ); // one value displayed by line
}
// just one value (a string)
else {
echo $custom_field;
}
}
<小時>
如果自定義字段數(shù)據(jù)是數(shù)組,可以在foreach循環(huán)中訪問數(shù)據(jù):
If the custom field data is an array, you can access the data in a foreach loop:
// Iterating in an array of keys/values
foreach( $custom_field as $key => $value ){
echo '<p>key: '.$key.' | value: '.$value.'</p>';
}
所有代碼都經(jīng)過測試且有效.
訂單中數(shù)據(jù)相關(guān)參考:
- 如何獲取 WooCommerce 訂單詳情(也適用于 woocommerce 3)
- 獲取訂單商品和 Woocommerce 3 中的 WC_Order_Item_Product
這篇關(guān)于如何獲取訂單商品 ID 以獲取一些產(chǎn)品元數(shù)據(jù)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!