Save the sum of all specific order item custom fields as order meta data in WooCommerce

◇◆丶佛笑我妖孽 提交于 2020-01-02 08:01:33

问题


Following my previous question " Save WooCommerce order item custom fields sum as a new meta data", when an order is placed, some order item custom meta data quantity, assemblycost and calculated_field (which value is to quantity x assemblycost) are saved.

How can I save as custom order meta data the sum of all order items calculated_field values?

For example, a sample order would look like so:

Product A:
assemblycost: 10
quantity: 2
calculated_field: 20

Product B:
assemblycost: 15
quantity: 2
calculated_field: 30

Product C: 
no assemblycost, quanity or calculated_field - custom fields present. 

Product D: 
assemblycost: 30
quantity: 2
calculated_field: 60

I want to create a new custom field for the order sum_calculated_fields , and set this equal to the sum of the calculated_fields in the order, so in the above example it would equal:

20+30+60 = 110.


回答1:


Updated: Here is the way to sum all the order item calculated_fields custom field and save that sum as custom order meta data:

add_action( 'woocommerce_checkout_create_order', 'action_checkout_create_order_callback', 10, 2 );
function action_checkout_create_order_callback( $order, $data ) {
    $calculated_fields_sum = 0; // Initializing

    // Loop Through order items
    foreach ( $order->get_items() as $item ) {
        if( $value = $item->get_meta('calculated_field') ) {
            $calculated_fields_sum += $value;
        }
    }
    // Update order meta data
    if( $calculated_fields_sum > 0 ) {
        $order->update_meta_data( 'calculated_fields_sum', $calculated_fields_sum );
    }
}

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



来源:https://stackoverflow.com/questions/55879116/save-the-sum-of-all-specific-order-item-custom-fields-as-order-meta-data-in-wooc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!