When a particular product is ordered in this WooCommerce store, two meta values are added to the order.
The two fields that store the meta values are located in wp_woocommerce_order_itemmeta
The meta keys are :
quantity
assemblycost
I want to create a new custom field programmatically when a new order is placed and set the value of this new field equal to quanity * assemblycost
if the meta key assemblycost exists for the product that has been ordered.
After some research I discovered that woocommerce_checkout_update_order_meta
is a hook that is executed after an order is saved to the database and the meta data has been updated. So this appears to be the hook I should use.
Ref: Add extra meta for orders in Woocommerce :
function add_item_meta( $order_id ) {
//global $woocommerce;
update_post_meta( $order_id, '_has_event', 'yes' );
}
I tried adding the following code, in functions.php:
add_action('woocommerce_checkout_update_order_meta',function( $order_id, $posted ) {
$assemblycost = wc_get_order_item_meta($order_id, 'assemblycost');
$quantity = wc_get_order_item_meta($order_id, 'quantity');
$calculatedValue = $quantity * $assemblycost;
wc_update_order_item_meta( $order_id, 'calculated_field', $calculatedValue );
} , 10, 2);
This does create the new meta field, however it sets the value to 0.
How can I change the code above so that the value of calculated_field is the multiplication of quantity * assemblycost
?