如何让WooCommerce变化价格有两位小数(尾随零)?

问题描述 投票:0回答:1

我有一个带变化的产品,由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;
}
woocommerce decimal price
1个回答
0
投票

我通过检查当价格有一个小数时修正它,加零。

// 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.