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

一笑奈何 提交于 2020-07-30 08:07:09

问题


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?


回答1:


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:

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



来源:https://stackoverflow.com/questions/52085847/custom-meta-data-added-to-woocommerce-not-displayed-in-order-item-meta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!