【问题标题】:Stylize woocommerce price decimals风格化 woocommerce 价格小数点
【发布时间】:2021-03-07 20:18:38
【问题描述】:

我想对价格标签中的小数进行样式化,并希望删除零个小数(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 美分!

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

我查了几个小时的谷歌并尝试了很多东西,我真的遇到了麻烦。我希望有人能把我引向正确的方向。

谢谢

【问题讨论】:

    标签: php woocommerce price


    【解决方案1】:

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

    然后将小数部分作为整数放入&lt;sup&gt; 标签内。
    如果价格是整数,&lt;sup&gt; 标签将包含"00"

    如果需要,您可以将自己的自定义 CSS 样式应用到 &lt;sup&gt; 标记,以根据需要对其进行格式化。

    // change the price formatting to apply a custom style to the decimals
    add_filter( 'formatted_woocommerce_price', 'custom_formatted_woocommerce_price', 10, 5 );
    function custom_formatted_woocommerce_price( $formatted_price, $price, $decimal_number, $separator, $thousand_separator ) {
        // if the price is float
        if ( floor( $price ) != $price ) {
            // gets the whole part
            $int = floor( $price );
            // gets the decimal part as an integer (based on the number of decimals set)
            $decimals = substr( $price, -$decimal_number );
        // if it is an integer
        } else {
            $int = $price;
            $decimals = '00';
        }
        // returns the price by separating the integer part from the decimals
        $formatted_price = '<span class="int">' . $int . $separator . '</span><sup>' . $decimals . '</sup>';
        return $formatted_price;
    }
    

    代码已经过测试并且可以运行。将其添加到活动主题的 functions.php 中。

    【讨论】:

    • 文森佐 感谢您的回复!我尝试将它添加到我的主题funcitons.php,结果价格为2位小数能够通过css设置样式,但是当我想为小数添加样式但当小数为00时,我需要修复什么而不是2零的消失。
    • 我设置了两个零以防价格已满。请参阅$decimals = '00'; 行。您可以修改此变量以更改整数的小数。
    • 非常感谢您的帮助。真的很感激,找了好几天!我不得不在价格后添加一个“-”号。因此,我通过修复将类添加到小数来做到了:$decimals = '&lt;span class="decimalentwee"&gt;-&lt;/span&gt;';
    猜你喜欢
    • 2019-03-29
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2021-12-08
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多