将所有特定订单商品自定义字段的总和保存为WooCommerce中的订单元数据

将所有特定订单商品自定义字段的总和保存为WooCommerce中的订单元数据

问题描述:

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.

按照上一个问题保存WooCommerce订单商品自定义字段总和为新的元数据” em>, 下订单时,某些订单商品自定义元数据数量 code>, assemblycost code>和 calculated_field code> (其值为数量 code> x assemblycost code>) em>已保存。 p>

如何将自定义订单元数据保存为所有订单商品 calculated_field code>值的总和? p>

例如,示例顺序如下: p>

 产品A:
assemblycost:10 
quantity:2 
calculated_field:  20 
 
产品B:
assemblycost:15 
quantity:2 
计算字段:30 
 
产品C:
no assemblycost,quanity或calculated_field  - 存在自定义字段。  
 
产品D:
assemblycost:30 
quantity:2 
计算字段:60 
  code>  pre> 
 
 

我想为订单 sum_calculated_fields创建一个新的自定义字段 code>,并将其设置为顺序中 calculated_fields code>的总和,因此在上面的示例中它将等于: p>

20 + 30 + 60 = 110. p> div>

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.