Saving custom WooCommerce cart data to order product item meta
I'm attempting to add meta data from the cart meta into the products in an order. So far I've been successful in adding a custom value to the products at the cart level (proved by outputting the values inline on the cart table), but once the final checkout has been done its not saving anywhere.
Adding to the cart (confirmed working):
function se_wc_add_product_order_type_cart( $cart_item, $product_id ) {
$product_order_type = $_POST['product_order_type'] ?? '';
if ( $product_order_type ) {
$cart_item['product_order_type'] = sanitize_text_field( $product_order_type );
}
return $cart_item;
}
add_filter( 'woocommerce_add_cart_item_data', 'se_wc_add_product_order_type_cart', 10, 2 );
Adding to the order from the cart (not working):
function se_wc_product_add_on_order_item_meta( $item, $cart_item_key, $values, $order ) {
$product_order_type = $values['product_order_type'] ?? '';
if ( ! empty( $product_order_type ) ) {
$item->add_meta_data( 'product_order_type', $product_order_type );
}
}
add_action( 'woocommerce_checkout_create_order_line_item', ' se_wc_product_add_on_order_item_meta', 10, 4 );
There's nothing being saved to the database (assuming its supposed to go in the
wp_woocommerce_order_itemmeta
table), and doing a
var_dump
on the
meta_data
field from the
woocommerce_order_item_get_formatted_meta_data
hook is empty - presumably again where it would show up.
If it matters, the product is a variable product and the site is a multisite.
Solutions
You can use below code to add item meta to order meta:
function se_wc_product_add_on_order_item_meta( $item_id, $values ) {
$product_order_type = $values['product_order_type'];
if ( ! empty( $product_order_type ) ) {
wc_add_order_item_meta($item_id,'product_order_type',$product_order_type);
}
}
add_action( 'woocommerce_new_order_item', ' se_wc_product_add_on_order_item_meta', 1, 2 );
Thanks.