如何使WooCommerce变异价格具有两个小数(尾随零)? [英] How to get WooCommerce variation prices to have two decimals (trailing zero)?

查看:83
本文介绍了如何使WooCommerce变异价格具有两个小数(尾随零)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有变体的产品,正在通过 templates/single-product/add-to-cart/variation.php 模板进行展示,该模板使用基于JavaScript的模板 {{{data.variation.display_price}}} .当我的价格以零结尾时,例如€12.50,前端的价格将显示为€12.5(不包含零).我想让价格包括尾随的零.

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;
}

推荐答案

我已通过检查价格是否为小数点后加零来对其进行修复.

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;
}

这篇关于如何使WooCommerce变异价格具有两个小数(尾随零)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆