WooCommerce 删除小数点后 3 位的额外零

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 美元”不会改变

您上面的过滤器(returns 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', 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$/', "", $formatted_price);
    }
    return $formatted_price;
}, 10, 4);

免责声明:代码未试用,直接写在答案框中。