Get the Metadata of an Order Item in Woocommerce 3

Get the metadata of an order item in woocommerce 3

Try the following:

// Get the $order object from an ID (if needed only)
$order = wc_get_order( $order_id);

// Loop through order line items
foreach( $order->get_items() as $item ){
// get order item data (in an unprotected array)
$item_data = $item->get_data();

// get order item meta data (in an unprotected array)
$item_meta_data = $item->get_meta_data();

// get only All item meta data even hidden (in an unprotected array)
$formatted_meta_data = $item->get_formatted_meta_data( '_', true );

// Display the raw outputs (for testing)
echo '<pre>' . print_r($item_meta_data, true) . '</pre>';
echo '<pre>' . print_r($formatted_meta_data, true) . '</pre>';
}

Related:

  • How to get WooCommerce order details
  • Get Order items and WC_Order_Item_Product in WooCommerce 3

Woocommerce how to get meta value from the order object

The following solutions have been fully tested on wordpress 5.8 and woocommerce 5+.
They're recommended, if you use update_post_meta to store your metadata as part of the order object.

Please keep in mind, if you're using third party plugins that store the metadata for you, then you may encounter discrepancies.

You could use the following ways to get your metadata:

$order_id = 12345;

$order = wc_get_order($order_id);

1- using $order->get_meta():

echo "<pre>";
print_r($order->get_meta('user_instagram'));
echo "</pre>";

2- using get_post_meta():

echo "<pre>";
echo get_post_meta($order->get_id(), 'user_instagram', true);
echo "</pre>";

3-using get_post_meta($order_id):

echo "<pre>";
print_r(get_post_meta($order_id)['user_instagram'][0]);
echo "</pre>";

4- using $order->get_meta_data():

echo "<pre>";
foreach ($order->get_meta_data() as $object) {
$object_array = array_values((array)$object);
foreach ($object_array as $object_item) {
if ('user_instagram' == $object_item['key']) {
print_r($object_item['value']);
break;
}
}
}
echo "</pre>";

Get specific WooCommerce order item metadata with non unique meta keys

As the order item meta data that you want has not a unique meta key (used multiple times), you will use WC_Order_Item get_formatted_meta_data() method, to get your custom order item meta data formatted in an array, as follows:

// Get the $order object from an ID (if needed only)
$order = wc_get_order( $order_id);

$data_output = array(); // Initializing

// Loop through order line items
foreach( $order->get_items() as $item ){
// get only All item meta data even hidden (in an unprotected array)
$formatted_meta_data = $item->get_formatted_meta_data( '_', true );

// Loop through order item custom meta data
foreach( $formatted_meta_data as $meta_data ){
// Targettting specific meta data (meta keys)
if( in_array( $meta_data->key, array('Carboidrato', 'Proteína', 'Guarnição') ) ) {
// Set data in a formated multidimensional array
$data_output[$meta_data->key][] = $meta_data->value;
}
}
}

## 1. Raw output (for testing): values grouped by metakey
echo '<pre>'; print_r($data_output); echo '</pre>';

## 2. Html Output (display): values grouped by metakey

// Loop through metakey / value pairs
foreach( $data_output as $key => $values ){
echo '<strong>' .strtoupper($key) . '</strong><br>';

echo '<ul>';

// Loop through values for the same meta key
foreach( $values as $value ) {
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}

Tested and works.

Raw data display for your custom formatted array will be like:

Array
(
[Carboidrato] => Array
(
[0] => Arroz Branco COM Feijão
[1] => Arroz Integral à Grega COM Feijão
[2] => Macarrão Alho Poró
)

[Proteína] => Array
(
[0] => Parmegiana Bovina
[1] => Parmegiana Frango
)

[Guarnição] => Array
(
[0] => Batata Rosthi Recheada com Requeijão
[1] => Farofa
)

)

For info: when the Order item meta data that you want has unique meta keys, you will use instead the WC_Data get_meta() method as follows:

// Get the $order object from an ID (if needed only)
$order = wc_get_order( $order_id);

// Loop through order line items
foreach( $order->get_items() as $item ){
// get specific order item data value from specific meta key
$carboidrato = $item->get_meta('Carboidrato');

// Output value for that metakey
echo '<p>' . __('Carboidrato') . ': ' . $carboidrato . '</p>';
}

Check for an order item meta data value in Woocommerce 3

As the order item metadata value is a of coma separated string, you can use strpos() this way:

$ops = $item->get_meta('Optionally select');
if( strpos( $ops, 'Sugar' ) !== false ) $skus[] = '50000';

Get protected custom order item meta data array from WooCommerce order

To get order item custom meta data, first you need to loop through order items, to be able to get that complex custom protected meta data using WC_Data method get_meta(). Then you will be able to get and calculate your "2nd installment cost as follows:

add_filter( 'woocommerce_get_order_item_totals', 'display_email_topay', 10, 2 );
function display_email_topay( $total_rows, $order ) {
$second_installment_cost = 0; // Initializing

// Loop through order items
foreach( $order->get_items() as $item ) {
// Try to get "_event_ticket_info" item meta value (array)
$event_ticket_data = $item->get_meta('_event_ticket_info');

// Get the data from the array
if( ! empty($event_ticket_data) ) {
// extract / Import variables into the current symbol table from an array
extract($event_ticket_data);
}

// if cost and quantity variables exist and have a value more than zero
if( isset($ticket_price) && $ticket_price > 0 && isset($ticket_qty) && $ticket_qty > 0 ) {
// Calculating and adding 2nd Installment cost item
$second_installment_cost += $ticket_price * $ticket_qty;
}
}

if ( $second_installment_cost > 0 ) {
$total_rows['recurr_not'] = array(
'label' => __( '2nd Installment', 'woocommerce' ),
'value' => wp_strip_all_tags( wc_price($second_installment_cost) )
);
}
return $total_rows;
}

Code goes in functions.php file of your active child theme (or active theme). It should works.

Related:

  • Get Order items and WC_Order_Item_Product in WooCommerce 3
  • Get the metadata of an order item in woocommerce 3

Get custom order item metadata in Woocommerce 3

Updated: Your code is really outdated since Woocommerce version 3… See:

  • How to get WooCommerce order details
  • Get Order items and WC_Order_Item_Product in Woocommerce 3

So your code should be:

$skus = $item_quantities = $line_item_totals = $items_meta_data = array();

// Loop though order items
foreach( $order->get_items() as $item_id => $item){
$product_id = $item->get_product_id();
$product = $item->get_product();

$item_quantities[] = $item->get_quantity();
$line_item_totals[] = $item->get_total();
$skus[] = $product->get_sku();
$items_meta_data[] = $item->get_meta_data();
}

// Product details for sending as one line to an external service
foreach ($skus as $key => $value){
$data .= "&product[".$key."]=".$value."";
$data .= "& product_kol[".$key."]=".$item_quantities[$key]."";
$data .= "& product_price[".$key."]=".$line_item_totals[$key]."";
if( isset($product_mod[$key]) ) {
$data .= "&product_mod[".$key."]=".$product_mod[$key]."";
}
}

It should work better… but $product_mod is not defined and $item->get_meta_data() is not used.


Now To get some custom meta data, if your custom meta key is Custom thing, you will use:

 $custom_thing = $item->get_meta('Custom thing');

This should be included in the foreach loop of order items… Tested and works.


Some other things:

  • To get the NON discounted order line item total: $item->get_subtotal();
  • To get the discounted order line item total: $item->get_total();
  • To get the product price (unit): $product->get-price();

Retrieve custom order item meta data values in Woocommerce 3

Using your custom order item meta data in woocommerce_payment_complete action hook (or in any other hook where you can get the order ID or the order object):

add_action( 'woocommerce_payment_complete', 'on_action_payment_complete', 10, 1 );
function on_action_payment_complete( $order_id ) {
// Get an instance of the WC_Order Object
$order = wc_get_order( $order_id );

// Loop through order items
foreach( $order->get_items() as $item_id => $item ){
$servicelevel = $item->get_meta('Service Level');
$servicecode = $item->get_meta('Your Reference');
$serviceprice = $item->get_meta('Sell Price');
$chargeweight = $item->get_meta('Charge Weight');
}
}

Code goes in function.php file of your active child theme (or active theme). It should works. The code inside the hook is tested and really works.

Add cart metadata to admin order screen in Woocommerce?

You must use the woocommerce_checkout_create_order_line_item hook to store the cart data as the order item meta data.

So:

add_action('woocommerce_checkout_create_order_line_item', 'save_custom_order_item_meta_data', 10, 4 );
function save_custom_order_item_meta_data( $item, $cart_item_key, $values, $order ) {

if ( isset( $values['polarity_information'] ) ) {
$item->update_meta_data( '_polarity_information', $values['polarity_information'] );
}

}

You can now access the order item meta data from the woocommerce_admin_order_data_after_order_details hook.

The code has been tested and worked. Add it to your active theme's functions.php.

RELATED ANSWERS

  • Save Woocommerce cart item custom data as order item meta data displaying it on orders and emails
  • How to get cart item key from order item in WooCommerce
  • Add and display custom cart item data in WooCommerce orders and emails
  • Update order meta with cart item custom data in Woocommerce 3

Access and display order item meta data in Woocommerce

To get all order item meta data, you will use WC_Order_Item get_formatted_meta_data() method with specific arguments, this way:

// Accessible non protected Order item meta data
$item_meta_data = $item->get_formatted_meta_data( '', true );

// Formatted raw Output
echo '<pre>'; print_r($item_meta_data); echo '</pre>';

To access some order item properties, you can use any WC_Order_Item_Product method like:

$item->get_product(); // Get the WC_Product object

$item->get_product_id(); // Get the Product ID

$item->get_variation_id(); // Get the Variation ID

$item->get_name(); // Get the Product name

$item->get_quantity(); // Get the item quantity

// and so on …

Then if you need to access a specific "custom" order item data value, you will use WC_Data get_meta() method:

$custom_value = $item->get_meta("_custom_key");

See: Get Order items and WC_Order_Item_Product in Woocommerce 3


Update (displaying your required custom order item meta data)

The data you need can be accessed and displayed this way:

if( $lessons = $item->get_meta('lessons') ) {
echo '<p>Lessons: '.$lessons.'</p>';
}

if( $tour_guide = $item->get_meta('tour guide') ) {
echo '<p>Tour Guide: '.$tour_guide.'</p>';
}

I hope that this works now.



Related Topics



Leave a reply



Submit