在 Woocommerce 3.2+ 中使用 Hooks 更改购物车总数

Vit*_*huk 1 php wordpress cart woocommerce hook-woocommerce

我想在 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;
}
Run Code Online (Sandbox Code Playgroud)

Loi*_*tec 9

从 Woocommerce 3.2 开始,这个钩子woocommerce_calculate_totals就不起作用了。
请参阅此线程的说明:在 WooCommerce 中更改购物车总价

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

1)过滤器钩子woocommerce_calculated_total这样:

add_filter( 'woocommerce_calculated_total', 'change_calculated_total', 10, 2 );
function change_calculated_total( $total, $cart ) {
    return $total + 300;
}
Run Code Online (Sandbox Code Playgroud)

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 );
}
Run Code Online (Sandbox Code Playgroud)

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