Juan David
Juan David

Reputation: 201

Trying to save order item meta data with woocommerce_new_order_item hook

/*
 * Add meta to order item
 * @param int $item_id
 * @param array $values
 * @return void
 */
function cart_add_meta_data_booking( $item_id, $values ) {
    if ( ! empty( $values['adults_qty'] ) ):
        wc_add_order_item_meta( $item_id, 'Adults', $values['adults_qty']);
    endif;
}
add_action( 'woocommerce_new_order_item', 'cart_add_meta_data_booking', 10, 2 );

I have updated my code because the previous function (woocommerce_add_order_item_meta) is deprecated, but I do not know why it does not work (wc_add_order_item_meta)

Upvotes: 2

Views: 3098

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254373

Since Woocommerce 3 and the new CRUD setters and getters methods, use this instead:

add_action( 'woocommerce_checkout_create_order_line_item', 'add_booking_order_line_item', 20, 4 );
function add_booking_order_line_item( $item, $cart_item_key, $values, $order ) {
    // Get cart item custom data and update order item meta
    if( isset( $values['adults_qty'] ) ){
        if( ! empty( $values['adults_qty'] ) )
            $item->update_meta_data( 'Adults', $values['adults_qty'] );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and work.

See this related explanations: Woocommerce: which hook to use instead of deprecated "woocommerce_add_order_item_meta"

Upvotes: 5

Related Questions