camelot camelot - 7 months ago 95
PHP Question

How to get order items ids to get some product meta data?

I'm trying to extract item meta value from Woocommerce's orders by using:

$data = wc_get_order_item_meta( $item, '_tmcartepo_data', true );

However, I can't find a way to get order_item_id as the first parameter (using 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;

And I mean this order item_id (1 and 2)

Order_item_id in database - Image

How can I don that?



— Update — (related to author comment)

You need $item['product_id'] to get your item ID (product ID) in the foreach loop for a WC order and to get some metadata of this product you have to use get_post_meta() function ( but NOT wc_get_order_item_meta() ). For array values don't use the third argument in get_post_meta() (as it's default argument is false for array values).

So here is your code:

global $post;
$order = wc_get_order( $post->ID );
$items = $order->get_items(); 

foreach ( $items as $item ) {

    $item_id = $item['product_id']; // <= Here is your product ID

    // Here you get your data (without "true" argument as it is an array)
    $data = get_post_meta( $item_id, '_tmcartepo_data'); 

    // To test data output (uncomment the line below)
    // print_r($data);

    echo $data[0]['value'];
    echo '<br>'; // to separate values
    echo $data[1]['value'];

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.