3

now with this function i can add new custom order item meta to all item of order.

add_action( 'woocommerce_add_order_item_meta', 'add_order_item_meta', 10, 2 );
function add_order_item_meta($item_id, $values) {
    $key = '_key'; 
    $value = '_value'; 
    wc_update_order_item_meta($item_id, $key, $value);
}

but how can i add different order item meta to each item of order? example i need to add each product price as order_itemmeta.

1 Answer 1

4

Try, woocommerce_checkout_create_order_line_item It has 4 available arguments and available after version WooCommerce 3.3+.

  • $item is an instance of WC_Order_Item_Product new introduced Class
  • $cart_item_key is the cart item unique hash key
  • $values is the cart item
  • $order an instance of the WC_Order object (This is a very useful additional argument in some specific cases)

In this hook we will replace the old working functions wc_add_order_item_meta() by the new WC_Data update_meta_data() method to be used with $item argument.

Example:

add_action( 'woocommerce_checkout_create_order_line_item', 'custom_checkout_create_order_line_item', 20, 4 );
function custom_checkout_create_order_line_item( $item, $cart_item_key, $values, $order ) {
    // Get a product custom field value
    $custom_field_value = get_post_meta( $item->get_product_id(), '_meta_key', true );
    // Update order item meta
    if ( ! empty( $custom_field_value ) ){
        $item->update_meta_data( 'meta_key1', $custom_field_value );
    }
    // … … Or … …

    // Get cart item custom data and update order item meta
    if( isset( $values['custom_data'] ) ) {
        $item->update_meta_data( 'meta_key2', $values['custom_data'] );
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.