phpwordpresswoocommercehook-woocommerceorders

Add a custom cart item value to WooCommerce order item meta data


I'm trying add order item meta and expect to see it in my {prefix}woocommerce_order_itemmeta table when user submit order.

I add my value with woocommerce_add_cart_item_data filter:

add_filter( 'woocommerce_add_cart_item_data', 'aa_func_20170206100217', 10, 3 );
function aa_func_20170206100217( $cart_item_data, $product_id, $variation_id ) {
    $data = $_POST;

    if ( isset( $data[ 'selected_date_event' ] ) ) {
        $selected_date_event = [
            'selected_date_event' => $data[ 'selected_date_event' ]
        ];

        return array_merge( $cart_item_data, $selected_date_event );
    }

    return $cart_item_data;
}

And this is works. When I var_dump my cart, there definitely my param exists.

enter image description here

But when user submit order, I can't find this param in my db.

What did I miss? How it can be stored in order item meta? And which is proper hook for this thing?


Solution

  • Update

    First in your code you need to sanitize the field value replacing:

    'selected_date_event' => $data[ 'selected_date_event' ]
    

    with:

    'selected_date_event' => sanitize_text_field( $data['selected_date_event'] )
    

    Then you need to save this cart item data as order item metadata with the following:

    // ADD THE INFORMATION AS ORDER ITEM META DATA SO THAT IT CAN BE SEEN AS PART OF THE ORDER
    add_action('woocommerce_checkout_create_order_line_item', 'add_product_custom_field_as_order_item_meta', 10, 4 );
    function add_product_custom_field_to_order_item_meta( $item, $cart_item_key, $values, $order ) {
        // the meta-key is 'Date event' because it's going to be the label too
        if( isset($values['selected_date_event']) && !empty($values['selected_date_event']) ) {
            $item->update_meta_data('Date event',  $values['selected_date_event']);
        }
    }
    

    *Code goes in functions.php file of your child theme (or in a plugin file).

    So this will be displayed as order item data on admin single order, on Order-received page, on My Account > Order view and on email notifications.

    Note that woocommerce_add_order_item_meta is deprecated since few years and not the best way to handle this problem.