在Woocommerce中以编程方式更新购物车总数

时间:2018-04-06 10:07:50

标签: php wordpress woocommerce cart hook-woocommerce

我想在结帐页面中按特定百分比更新我的购物车总数。就像在自定义PHP中一样,$cart = $cart_total - ($cart_total * 0.15); 我在functions.php

中写了以下内容
add_action( 'woocommerce_review_order_before_order_total', 'custom_cart_total' );
add_action( 'woocommerce_before_cart_totals', 'custom_cart_total' );

function custom_cart_total($discount_percentage) {
// actual cart amount is = $195.00
// $discount_percentage = 0.15;
$actual = WC()->cart->total;
WC()->cart->total =+ (WC()->cart->total *= $discount_percentage);
WC()->cart->total =- WC()->cart->total + $actual;

echo $ordertotal = wp_kses_data( WC()->cart->get_total() ); //die();
// $ordertotal is showing the expected amount $165.75;
return WC()->cart->total += $ordertotal; // It shows the $195.00
exit();
}

购物车仍然显示195.00美元,但应该是165.75美元; 如何修改功能?

1 个答案:

答案 0 :(得分:1)

您没有使用正确的挂钩...请尝试以下方法:

add_filter( 'woocommerce_calculated_total', 'custom_calculated_total', 10, 2 );
function custom_calculated_total( $total, $cart ){
    return round( $total - ($total * 0.15), $cart->dp );
}

代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作。