【问题标题】:Change Cart total using Hooks in Woocommerce 3.2+在 Woocommerce 3.2+ 中使用 Hooks 更改购物车总数
【发布时间】:2019-01-29 18:59:31
【问题描述】:

我想在 woocommerce 结帐页面上的订单总数中添加 300,但 woocommerce_calculate_totals 钩子不起作用...

如果我使用 var_dump($total),我会看到正确的结果 - int(number),但订单表中的总金额没有变化。

add_action( 'woocommerce_calculate_totals', 'action_cart_calculate_totals', 10, 1 );

function action_cart_calculate_totals( $cart_object) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( !WC()->cart->is_empty() ):


        $total = $cart_object->cart_contents_total += 300;

        var_dump($total);

    endif;
}

【问题讨论】:

    标签: php wordpress woocommerce cart hook-woocommerce


    【解决方案1】:

    自 Woocommerce 3.2 以来,钩子 woocommerce_calculate_totals 不再适用。
    请参阅此线程的解释:Change Cart total price in WooCommerce

    您必须使用以下方式之一:

    1) 过滤器钩子woocommerce_calculated_total 这样:

    add_filter( 'woocommerce_calculated_total', 'change_calculated_total', 10, 2 );
    function change_calculated_total( $total, $cart ) {
        return $total + 300;
    }
    

    2) 费用 API,例如:

    add_action( 'woocommerce_cart_calculate_fees', 'add_custom_fee', 10, 1 );
    function add_custom_fee ( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        $fee = 300;
    
        $cart->add_fee( __( 'Fee', 'woocommerce' ) , $fee, false );
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件或任何插件文件中。

    【讨论】:

    • 谢谢。它工作正常!一个问题:你为什么在你的函数'change_calculated_total'中使用第二个参数$cart。
    • @VitKashchuk 我没有在这里使用第二个参数,我只是将其设置为应有的值:记住答案对其他人有用。 现在看来这个答案要回答您的问题,请accept回答,谢谢。
    • 确实还是有用的@VitKashchuk
    • @LoicTheAztec 如何将参数传递给此 change_calculated_total 。我想传递来自购物车页面的用户输入值。
    猜你喜欢
    • 2017-09-10
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    相关资源
    最近更新 更多