If you need to get add-ons data from the order, you can use the following function. You’ll see that the function includes two ways to get metadata – first, to iterate through all metadata in each line item. Second, to return the value of a specific metakey:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get add-on metadata from each line item in the order | |
* @param $order_id | |
* @param $metakey The add-ons metakey (field label), usually prefixed by an underscore | |
*/ | |
function prefix_get_addons_metadata_by_key( $order_id, $metakey=false ) { | |
$order = wc_get_order( $order_id ); | |
$order_line_items = $order->get_items(); | |
foreach( $order_line_items as $line_item ) { | |
// Here, we can iterate through all the meta for this line item | |
$all_meta = $line_item->get_meta_data(); | |
if( $all_meta ) { | |
foreach( $all_meta as $meta ) { | |
$meta_id = $meta->id; | |
$meta_key = $meta->key; | |
$meta_value = $meta->value; | |
} | |
} | |
// Here, we can get the value by a specific metakey | |
if( $metakey ) { | |
$meta_value = $line_item->get_meta( $metakey ); | |
} | |
} | |
} |