WooCommerce: add different order item meta for each item in order

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'] );
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)