In WooCommerce, you can use the woocommerce_checkout_create_order action to create post meta data for the subtotal at the time of checkout, which you can then use for future calculations.

Here is an example of how you can use the woocommerce_checkout_create_order action to create post meta data for the subtotal:

Copy codeadd_action( 'woocommerce_checkout_create_order', 'add_subtotal_to_order', 10, 2 );
function add_subtotal_to_order( $order, $data ) {
    $subtotal = WC()->cart->subtotal;
    $order->update_meta_data( 'subtotal', $subtotal );
    $order->save();
}

This code uses the woocommerce_checkout_create_order action to create post meta data for the subtotal, it gets the subtotal from the cart object and adds it to the order as a custom meta field, it then saves the order.

You can then use this subtotal meta data for any calculations you want, for example:

Copy code$subtotal = get_post_meta( $order_id, 'subtotal', true );
$discount = calculate_discount( $subtotal );
$order->update_meta_data( 'discount', $discount );
$order->save();

You can also use the woocommerce_checkout_update_order_meta action to update the order meta data after the order is placed.

It’s important to note that you should use this code snippet on the checkout page and after the woocommerce_init action is fired, so that the WC() object is available.

Also, make sure to check if the subtotal is exists before trying to use it and also be aware that you should use the correct way to access the cart object based on the version of WooCommerce you are using.

(Visited 10 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window