问题
I have a product with variations, that is being displayed by the templates/single-product/add-to-cart/variation.php
template, which uses JavaScript-based templates {{{ data.variation.display_price }}}
. When I have price that end with a zero, for example, € 12.50, the price on the front-end will be displayed as € 12.5 (without the zero). I want to have the price include the trailing zero.
I've tried the following filter, but it does not work.
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;
}
回答1:
I've fixed it by checking that when the price has one decimal, add a zero.
// 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;
}
来源:https://stackoverflow.com/questions/55393020/how-to-get-woocommerce-variation-prices-to-have-two-decimals-trailing-zero