cam*_*lot 13 php wordpress product orders woocommerce
我试图通过使用以下方法从Woocommerce的订单中提取项目元值:
$data = wc_get_order_item_meta( $item, '_tmcartepo_data', true );
Run Code Online (Sandbox Code Playgroud)
但是,我找不到将order_item_id作为第一个参数的方法(使用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;
}
Run Code Online (Sandbox Code Playgroud)
我的意思是这个订单item_id(1和2)
我该怎么办?
谢谢.
Loi*_*tec 20
2018年更新:
- 用2种可能的案例澄清答案
- 增加了woocommerce 3+的兼容性
所以可能有两种情况:
1)获取产品元数据(未在订单项元数据中设置):
您将需要得到的产品ID在foreach循环中的一个WC_Order,并获得了此产品,您西港岛线使用一些元数据get_post_meta()功能(但不是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;
}
}
Run Code Online (Sandbox Code Playgroud)
2)获取订单商品元数据(自定义字段值):
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果自定义字段数据是数组,则可以在foreach循环中访问数据:
// Iterating in an array of keys/values
foreach( $custom_field as $key => $value ){
echo '<p>key: '.$key.' | value: '.$value.'</p>';
}
Run Code Online (Sandbox Code Playgroud)
所有代码都经过测试和运行.
与订单中的数据相关的参考:
在进行foreach时$order->get_items(),他们的密钥实际上是订单ID.所以:
foreach ( $order->get_items() as $key => $item ) {
$data = wc_get_order_item_meta( $key, '_tmcartepo_data' );
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43184 次 |
| 最近记录: |