Saving a product meta field to order item meta in WooCommerce
First time posting...so hopefully I've done this correctly. :)
I'm currently working on a snippet to save a custom product field (purchase price) into the order item meta. The reason that we want to do this is that the purchase price changes during the time where orders are accepted. In order to produce accurate reporting - we need to know what the purchase price field (custom product field) was set to when the order was placed. Simply exporting the custom field (_wcj_purchase_price) gives the current value, which may not be current.
The custom field that stores the purchase price is called _wcj_purchase_price and I am trying to create a custom order item meta field called _purchase_price which is added at the time the order is created.
This is the code that I've got so far, from my attempts, but it's not working quite right. I am sure the answer is obvious to someone, but I'm very stuck at the moment!
add_action( 'wc_add_order_item_meta', 'save_item_sku_order_itemmeta', 10, 3 );
function save_item_sku_order_itemmeta( $item_id, $values, $cart_item_key ) {
$purchasep = get_post_meta( $values[ 'product_id' ], '_wcj_purchase_price', true );
wc_add_order_item_meta( $item_id, '_purchase_price', $purchasep , false );
}
Any ideas or advice? Please let me know if anything is unclear.
Thank you very much!
Solutions
Are you sure that there is a filter called "wc_add_order_item_meta"?
Correct filter for this case can be woocommerce_new_order.
add_action('woocommerce_new_order', function ($order_id) {
// your code here
}, 10, 1);
For exampe, you can use such code:
add_action('woocommerce_new_order', function ($order_id) {
$order = wc_get_order( $order_id );
foreach( $order->get_items() as $item_id => $item ){
$product_id = $item->get_product_id();
$purchasep = get_post_meta( $product_id, '_wcj_purchase_price', true );
wc_add_order_item_meta($item_id, '_purchase_price', $purchasep , false );
}
}, 10, 1);