php – Change order total after checkout in Woocommerce-ThrowExceptions

Exception or error:

I cant seem to find which hook to use to change the total (or any variable of the cart) after user clicks checkout. So for example, user Submits the Checkout form and then I need to do some checks and change the total accordingly.

How should I do that, which hook do I use?

How to solve:

This can be done in woocommerce_checkout_create_order action hook, where you will have to use CRUD getters and setters methods for WC_Abstract_Order and WC_Order classes…

As cart object and cart session has not been destroyed yet, you can still also use WC()->cart object and WC_Cart methods, to get data…

This hook is triggered just before the order data is saved in database with $order->save();. You can see that in the source code HERE.

Below a fake working example:

add_action( 'woocommerce_checkout_create_order', 'change_total_on_checking', 20, 1 );
function change_total_on_checking( $order ) {
    // Get order total
    $total = $order->get_total();

    ## -- Make your checking and calculations -- ##
    $new_total = $total * 1.12; // <== Fake calculation

    // Set the new calculated total
    $order->set_total( $new_total );

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

Tested and works.

Some explanations here: Add extra meta for orders in Woocommerce

Leave a Reply

Your email address will not be published. Required fields are marked *