[英]WooCommerce Remove Extra Zero in 3 Decimal
我使用 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
掛鈎。
以下過濾器將刪除所有尾隨零:
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', 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 = preg_replace('/^(\d+' . preg_quote($decimal_separator, '/' ) . '\d{2})0$/', "$1", $formatted_price);
}
return $formatted_price;
}, 10, 4);
免責聲明:代碼未試過,直接寫在答案框中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.