Change order total after checkout in Woocommerce

∥☆過路亽.° 提交于 2019-12-22 22:23:02

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/49036503/change-order-total-after-checkout-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!