How to get order items ids to get some product meta data?
2018 Update:
- Clarifying the answer with 2 possible cases
- Added compatibility for woocommerce 3+
So There can be 2 cases:
1) Get product meta data (not set in order item meta data):
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()
).
So here is your code:
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) Get order item meta data (custom field value):
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; }}
If the custom field data is an array, you can access the data in a foreach loop:
// Iterating in an array of keys/valuesforeach( $custom_field as $key => $value ){ echo '<p>key: '.$key.' | value: '.$value.'</p>';}
All code is tested and works.
Reference related to data in orders:
- How to get WooCommerce order details (also for woocommerce 3)
- Get Order items and WC_Order_Item_Product in Woocommerce 3
When doing the foreach on $order->get_items()
, their key is actually the orderline ID. So:
foreach ( $order->get_items() as $key => $item ) { $data = wc_get_order_item_meta( $key, '_tmcartepo_data' ); ...}
Late to the party, but being working with the same point with TM Extra Product Options plugin, I think this is what answers your question:
$order = wc_get_order( $post->ID );$items = $order->get_items();foreach( $items as $item ){ $data = unserialize($item['item_meta']['_tmcartepo_data'][0]); $a = $data[0]['value']; $b = $data[1]['value']; echo $a; echo $b;}
Tested and works in my case.