在WooCommerce中,购物车总数和小数最接近的5个单位



我一直在研究购物车价值汇总到最接近的值并创建了一个函数,但它舍入了完整的值。

我做错了什么?

//round cart total up to nearest dollar
add_filter( 'woocommerce_calculated_total', 'custom_calculated_total' );
function custom_calculated_total( $total ) {
$total = round( $total );
return ceil($total / 5) * 5;
}

如果我有值44.24我想输出为44.25,如果我的值为44.28,则输出应为44.30

首先,除了woocommerce_calculated_total过滤器钩之外,您还需要使用woocommerce_cart_subtotal过滤器钩。 否则你的小计会偏离总计,这看起来很奇怪

然后,您可以使用以下答案之一: 舍入机制到最接近的 0.05

所以你得到:

function rnd_func( $x ) {
return round( $x * 2, 1 ) / 2;
}
function filter_woocommerce_cart_subtotal( $subtotal, $compound, $cart ) {
// Get cart subtotal
$round = rnd_func( $cart->subtotal );

// Use wc_price(), for the correct HTML output
$subtotal = wc_price( $round );
return $subtotal;
}
add_filter( 'woocommerce_cart_subtotal', 'filter_woocommerce_cart_subtotal', 10, 3 );
// Allow plugins to filter the grand total, and sum the cart totals in case of modifications.
function filter_woocommerce_calculated_total( $total, $cart ) {    
return rnd_func( $total );
}
add_filter( 'woocommerce_calculated_total', 'filter_woocommerce_calculated_total', 10, 2 );

最新更新