所以我目前正在开发一个销售散装谷物和香料的网站。
1个产品的单位是1克。我将产品的最小订购量设置为 100 单位(100 克)。但 1 克的价格可能非常低(有时 0.0045 美元,所以 1 克甚至不到半美分)。
我还设置了下订单的最低金额,并且购物车的总金额必须至少为 15 美元。
有时购物车的总金额会是小数点后 4 位的金额,例如 $20.5517 。我希望购物车中显示的小计价格和总价格四舍五入到小数点后两位。但我需要将商品价格保留到小数点后 4 位,因为这是我保持价格竞争力的唯一方法。¸
基本上,我需要后端保留 4 位小数价格,并在产品上显示 4 位小数(这就是它已经设置的方式),但我希望在客户可以通过 PayPal 付款之前对总数进行四舍五入。
有人可以帮我吗?
谢谢
这是一个解决方案。但您必须自己对 woocommerce 相关模板进行所有必要的更改。
首先,如果您不知道如何正确自定义 WooCommerce 模板,请阅读以下内容:
模板结构 + 通过主题覆盖模板
然后现在使用下面的自定义函数将完成显示的格式化 html 价格的工作(将价格从 4 位小数更改为 2 位小数并保留 html 标签),您将能够对 woocommerce 相关模板进行必要的更改:
function wc_shrink_price( $price_html ){
// Extract the price (without formatting html code)
$price = floatval(preg_replace('/[^0-9\.,]+/', '', $price_html));
// Round price with 2 decimals precision
$shrink_price = round($price, 2);
// Replace old existing price in the original html structure and return the result
return str_replace($price, $shrink_price, $price_html);
}
代码位于活动子主题(或主题)的 function.php 文件中,或者也位于任何插件文件中。
此代码经过测试并且可以工作
使用示例:
在 woocommerce 模板
cart/cart_totals.php
的第 33
行,您有以下原始代码:<td data-title="<?php esc_attr_e( 'Subtotal', 'woocommerce' ); ?>"><?php wc_cart_totals_subtotal_html(); ?></td>
wc_cart_totals_subtotal_html()
函数,您将看到正在使用此 WC_Cart
方法:WC()->cart->get_cart_subtotal()
… <td data-title="<?php esc_attr_e( 'Subtotal', 'woocommerce' ); ?>">
<?php
// Replacement function by a WC_Cart method
$subtotal_html_price = WC()->cart->get_cart_subtotal();
// Here we use our custom function to get a formated html price with 2 decimals
echo wc_shrink_price( $subtotal_html_price );
?>
</td>
因此,正如您所见,您需要对所有购物车价格执行类似的操作。
购物车和结账模板位于
cart
和 checkout
子文件夹中…