woocommerce - 如何让 WooCommerce 变化价格具有两位小数(尾随零)?
问题描述
我有一个带有变体的产品,它由templates/single-product/add-to-cart/variation.php
模板显示,它使用基于 JavaScript 的模板{{{ data.variation.display_price }}}
。当我的价格以零结尾时,例如 12.50 欧元,前端的价格将显示为 12.5 欧元(没有零)。我想让价格包括尾随零。
我尝试了以下过滤器,但它不起作用。
add_filter( 'woocommerce_price_trim_zeros', 'wc_hide_trailing_zeros', 10, 1 );
function wc_hide_trailing_zeros( $trim ) {
// set to false to show trailing zeros
return false;
}
解决方案
我已经通过检查当价格有一位小数时添加一个零来修复它。
// https://stackoverflow.com/a/2430214/3689325
function numberOfDecimals( $value ) {
if ( (int) $value == $value ) {
return 0;
}
else if ( ! is_numeric( $value ) ) {
return false;
}
return strlen( $value ) - strrpos( $value, '.' ) - 1;
}
/**
* Make sure prices have two decimals.
*/
add_filter( 'woocommerce_get_price_including_tax', 'price_two_decimals', 10, 1 );
add_filter( 'woocommerce_get_price_excluding_tax', 'price_two_decimals', 10, 1 );
function price_two_decimals( $price ) {
if ( numberOfDecimals( $price ) === 1 ) {
$price = number_format( $price, 2 );
return $price;
}
return $price;
}
推荐阅读
- python - 尝试创建同一类的多个实例时无法腌制 _tkinter.tkapp 对象错误
- php - Symfony 3.4 出现错误“2006 MySQL 服务器已消失”
- r - R:警告消息:包“ade4”是用 R 3.4.4 版本编译的
- mysql - MySQL 安装程序未在 Windows 7、32 位中安装 MySQL 服务器
- java - 使用不同的根对象类型调用相同的 Spring EL 表达式失败
- python - Unicode 字符串的 32 位整数表示
- azure - 我可以为 Azure Function 分配保留的 IP 吗?
- database - 如何一次将 101 个 CSV 文件导入我的 PostgreSQL 数据库?
- c++ - 为什么 struct 属性声明和初始化顺序会这样?
- database - HANA 中的日期格式选项