3

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?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Shile
  • 1,063
  • 3
  • 13
  • 30

1 Answers1

14

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

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Thanks for this, i spent a lot of time searching and couldnt find this particular hook. – Shile Mar 01 '18 at 00:57
  • Sorry for bothering you again, but how do i set the subtotal and product price in the same process? There is no setter like set_subtotal() in the WC_Abstract_Order. – Shile Mar 01 '18 at 15:50
  • 1
    @Shile for order subtotal that is much more complicated as it's a calculated amount based on line items… so you should better ask a new question, with the minimal code you have tried and some related details about what you want to do and what you are checking… for line items you should look at [`WC_Checkout` `create_order_line_items()` method source code](https://docs.woocommerce.com/wc-apidocs/source-class-WC_Checkout.html#353-391) – LoicTheAztec Mar 01 '18 at 16:03