How to get WooCommerce variation prices to have two decimals (trailing zero)?

风流意气都作罢 提交于 2021-01-29 06:23:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!