猿问

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;

}

但是,它无法正常工作。因为它只删除 0.000 位小数。(20.000 美元到 20 美元)

此外,我想从最后一个小数段删除额外的 0 小数。


例如; “$20.000”改为“$20.00”

“$20.050”改为“$20.05”

“$20.055”不会改变


慕工程0101907
浏览 120回答 1
1回答

PIPIONE

您的上述过滤器(返回)会触发functiontrue的执行,该函数确实仅在价格只有 0 位小数时才删除零。wc_trim_zeros()你需要的是使用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);免责声明:代码未经尝试,直接写在答案框中。
随时随地看视频慕课网APP
我要回答