简体   繁体   中英

Save WooCommerce order item custom fields sum as a new meta data

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 ?

This is related to order items and should be saved as order item meta data but not as order meta data.

Now this should be saved at the same time than your 2 custom fields quantity and assemblycost . So you should provide in your question the related code that save quantity and assemblycost as order item meta data.

You can try the following (but I am not sure that I will work):

add_action( 'woocommerce_checkout_create_order_line_item', 'action_checkout_create_order_line_item_callback', 1000, 4 );
function action_checkout_create_order_line_item_callback( $item, $cart_item_key, $cart_item, $order ) {
    $quantity     = $item->get_meta('quantity');
    $assemblycost = $item->get_meta('assemblycost');
    if( isset($quantity) && isset($assemblycost) ) {
        $item->update_meta_data( 'calculated_field', $quantity * $assemblycost );
    }
}

Code goes in function.php file of your active child theme (or active theme).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM