In WooCommerce, with this code, i'm using product custom fields to add some custom metadata to order items when making a purchase. I also need to auto add some of this custom metadata to the customer Order Notes (basically so it gets sent to my shipping fulfillment service).
Below is the code i'm currently using:
add_action('woocommerce_checkout_create_order', 'before_checkout_create_order', 20, 2);
function before_checkout_create_order( $order, $data ) {
$items_in_order=array();
foreach( $order->get_items() as $item_id => $item ) {
$product = $order->get_product_from_item( $item );
$text = $product->get_sku();
$bags_count = array(
'neutral_bags' => 0,
'bright_bags' => 0,
'pastel_bags' => 0,
'reg_tendons' => 0,
'gid_tendons' => 0
);
$meta_key1 = __('Neutral Bags', 'woocommerce');
$meta_key2 = __('Bright Bags', 'woocommerce');
$meta_key3 = __('Pastel Bags', 'woocommerce');
$meta_key4 = __('Reg Tendons', 'woocommerce');
$meta_key5 = __('GID Tendons', 'woocommerce');
$bags_count['neutral_bags'] += wc_get_order_item_meta( $item_id, $meta_key1, true );
$bags_count['bright_bags'] += wc_get_order_item_meta( $item_id, $meta_key2, true );
$bags_count['pastel_bags'] += wc_get_order_item_meta( $item_id, $meta_key3, true );
$bags_count['reg_tendons'] += wc_get_order_item_meta( $item_id, $meta_key4, true );
$bags_count['gid_tendons'] += wc_get_order_item_meta( $item_id, $meta_key5, true );
$text .= ' | ' . $bags_count['neutral_bags'];
$text .= ' | ' . $bags_count['bright_bags'];
$text .= ' | ' . $bags_count['pastel_bags'];
$text .= ' | ' . $bags_count['reg_tendons'];
$text .= ' | ' . $bags_count['gid_tendons'];
array_push( $items_in_order , $text );
}
$text = implode('<br/>', $items_in_order );
// get customer note
$note = $order->get_customer_note();
// Merging existing customer note with bags count (if it exist)
$note = empty( $note ) ? $text : $note . '<br/>' . $text . ' V1';
// Set the new customer note before saving
$order->set_customer_note( $note );
}
As per the below screenshot, you'll see the data is saved to the product, but doesn't get pulled into the order notes section correctly.
Any ideas why this might be?