Get the metadata of an order item in woocommerce 3

Manu picture Manu · Feb 1, 2018 · Viewed 26.7k times · Source

how to get metadata of a product woocommerce? I have field custom en my products and I need to get this data.

{"ID":151,
 "ORDER_ID":251,
 "NAME":"car",
 "PRODUCT_ID":87,
 "VARIATION_ID":0,
 "QUANTITY":1,
 "TAX_CLASS":"",
 "SUBTOTAL":"3",
 "SUBTOTAL_TAX":"0",
 "TOTAL":"3",
 "TOTAL_TAX":"0",
 "TAXES":{"TOTAL":[],
          "SUBTOTAL":[]},
 "META_DATA":[{"ID":1433,
               "KEY":"my_car",
               "VALUE":"red"}]}

But the always result is the same, I can't access to field meta_data. The field ID and name I have access.

I used get_data() and get_item(), but when I try access with get_data() to field meta_data it give me this error:

 UNCAUGHT ERROR: CANNOT USE OBJECT OF TYPE WC_DATETIME AS ARRAY IN  

And with get_item(), the value meta_data is null because is protected.

How can i get these values?

Answer

LoicTheAztec picture LoicTheAztec · Feb 1, 2018

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: