如何解决WooCommerce以3个十进制删除多余的零
我使用的是小数点后3位,因此我的价格为:
“ $ 20.000”,“ $ 20.050”,“ $ 20.055”
我搜索了删除零个小数,并找到了一个:
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 true;
}
但是,它不能正常工作。因为它仅删除.000小数。 (从$ 20.000到$ 20)
此外,我想从最后一个小数部分中删除多余的0个小数。
例如;
“ $ 20.000”至“ $ 20.00”
从“ $ 20.050”到“ $ 20.05”
“ $ 20.055”不会更改
解决方法
您上方的过滤器(返回true
)将触发执行wc_trim_zeros()
function,只有在价格只有小数点后0时,该过滤器才删除零。
您需要使用formatted_woocommerce_price
hook。
以下过滤器将剪切所有尾随的零:
add_filter('formatted_woocommerce_price',function($formatted_price,$price,$decimals,$decimal_separator) {
// Need to trim 0s only if we have the decimal separator present.
if (strpos($formatted_price,$decimal_separator) !== false) {
$formatted_price = rtrim($formatted_price,'0');
// After trimming trailing 0s,it may happen that the decimal separator will remain there trailing... just get rid of it,if it's the case.
$formatted_price = rtrim($formatted_price,$decimal_separator);
}
return $formatted_price;
},10,4);
更新:以下代码仅在末尾的第三个和最后一个十进制时才切掉尾随的零:
add_filter('formatted_woocommerce_price',$decimal_separator) !== false) {
$formatted_price = preg_replace('/^(\d+' . preg_quote($decimal_separator,'/' ) . '\d{2})0$/',"$1",$formatted_price);
}
return $formatted_price;
},4);
免责声明:代码未尝试过,直接写在答案框中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。