程式化 woocommerce 价格小数

Stylize woocommerce price decimals

我想对价格标签中的小数点进行样式化,并希望删除零个小数点(190,00 之前),它应该是(190,- 之后)

以及“,”后面的小数点,我想像这张演示图片一样变小:

所以首先我想用 functions.php

中的这一行删除小数
add_filter( 'woocommerce_price_trim_zeros', '__return_true' );

至少它删除了零,因为它应该是:

这就是带小数点的价格 我想缩小价格:

经过一番搜索,我发现了一段代码,它可以使小数点变小。所以我用这段代码做了这个:

add_filter( 'formatted_woocommerce_price', 'ts_woo_decimal_price', 10, 5 );function ts_woo_decimal_price( $formatted_price, $price, $decimal_places, $decimal_separator, $thousand_separator ) {
$unit = number_format( intval( $price ), 0, $decimal_separator, $thousand_separator );
$decimal = sprintf( '%02d', ( $price - intval( $price ) ) * 100 );
return $unit . $decimal_separator. '<sup>' . $decimal . '</sup>';

}

所以现在价格看起来不错,但奇怪的是,价格比变小之前低了1美分!

现在的问题是,零位小数消失的价格现在又回来了....

我检查了 google 几个小时并尝试了很多东西,我真的很麻烦。我希望有人能指引我正确的方向。

谢谢

您可以查看此答案Check if number is decimal 检查价格是否为小数

然后你得到小数部分作为一个整数并把它放在<sup>标签里。

如果需要,您可以将自己的自定义 CSS 样式应用到 <sup> 标签,以根据需要设置格式。

编辑: 修复了@ClawDuda 报告的一位小数格式错误。

// Edit the output by showing decimals with the HTML <sup> tag.
add_filter( 'formatted_woocommerce_price', 'custom_formatted_woocommerce_price', 10, 5 );
function custom_formatted_woocommerce_price( $formatted_price, $price, $decimal_number, $separator, $thousand_separator ) {
    // Gets the integer and decimal part of the product price.
    $raw_price = explode( $separator, $price );
    $int       = $raw_price[0];
    $decimals  = isset( $raw_price[1] ) ? $raw_price[1] : 0;
    // Edit the output.
    $formatted_price = '<span class="int">' . $int . $separator . '</span><sup>' . str_pad( $decimals, $decimal_number, '0', STR_PAD_RIGHT ) . '</sup>';
    return $formatted_price;
}

输出:

代码已经过测试并且可以工作。将它添加到您的活动主题 functions.php.