Search code examples
phpwordpresswoocommercehook-woocommerceorders

Custom meta data added to Woocommerce not displayed in order item meta


I've a single piece of custom metadata to a WooCommerce order and now I want to display this on the thank you page after checkout, however, the data isn't available. The data is saved and available in the admin, I just can't seem to access it.

function custom_order_item_meta( $item_id, $values ) {

    if ( ! empty( $values['custom_option'] ) ) {
        woocommerce_add_order_item_meta( $item_id, 'custom_option', $values['custom_option'] );           
    }
}
add_action( 'woocommerce_add_order_item_meta', 'custom_order_item_meta', 10, 2 );

But when I dump out the wc_get_order my meta data isn't there.

I'm using;

woocommerce_add_order_item_meta() to save the data but dumping out var_dump(wc_get_order( $order->id )); also doesn't show my custom meta field

is there another hook I should be using to access this data?


Solution

  • The data that you are looking for is not order meta data, but order item meta data and is located in wp_woocommerce_order_itemmeta database table (see below how to access this data).

    Since woocommerce 3, a much better hook replace old woocommerce_add_order_item_meta hook.

    Displayed and readable order item meta data:

    To make custom order item meta data displayed everywhere, the meta key should be a readable label name and without starting by an underscore, as this data will be displayed under each order item.

    The code:

    add_action( 'woocommerce_checkout_create_order_line_item', 'custom_order_item_meta', 20, 4 );
    function custom_order_item_meta( $item, $cart_item_key, $values, $order ) {
        if ( isset( $values['custom_option'] ) ) {
            $item->update_meta_data( __('Custom option', 'woocommerce'), $values['custom_option'] );          
        }
    }
    

    In "Order received" (thankyou) page, you will get something like:

    enter image description here

    This will be displayed too in backend and email notifications.

    To access this order item data you need to get items from the order object in a foreach loop:

    foreach( $order->get_items() as $item_id => $item ){
    
        $custom_data = $item->get_meta( 'Custom option' );
    }
    

    To Get the first order item (avoiding a foreach loop), you will use:

    $items       = $order->get_items(); // Order items
    
    $item        = reset($items); // The first Order item
    $custom_data = $item->get_meta( 'Custom option' ); // Your custom meta data
    

    Related: Replace woocommerce_add_order_item_meta hook in Woocommerce 3.4