问题
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