duancanjiu3754 2018-02-28 18:46
浏览 255
已采纳

在Woocommerce结账后更改订单总额

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条回答 默认 最新

  • doufenpaiyu63706 2018-02-28 23:32
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?