【问题标题】:How can I round up the price in WooCommerce?如何在 WooCommerce 中四舍五入价格?
【发布时间】:2020-05-16 12:48:05
【问题描述】:

我想知道是否有办法四舍五入 WooCommerce 中的价格保持显示 2 位小数(因此价格将以第一个和第二个小数 ,00 结尾)。

例如:12.54 欧元将四舍五入为 13.00 欧元,145.67 欧元将四舍五入为 146.00 欧元。

我正在使用插件来打折产品价格,即 39,00 欧元 - 20% = 35,10 欧元(应该变成 36,00 欧元)。

我想按照前面的解释对所有价格进行四舍五入。

有没有办法做到这一点?

【问题讨论】:

    标签: php wordpress woocommerce product price


    【解决方案1】:

    您无法真正汇总全球所有真实计算价格,例如税金、运费、折扣、总计和其他第三方插件计算的价格。四舍五入计算的价格需要逐案进行......

    您只能在全球范围内对所有“显示”格式的价格进行四舍五入,保留 2 位小数。为此,有两个步骤解释如下:

    1) 以下挂钩函数将对 WooCommerce 中显示的原始价格进行四舍五入:

    如有必要,它将通过四舍五入返回下一个最大的整数值。

    add_filter( 'raw_woocommerce_price', 'round_up_raw_woocommerce_price' )
    function round_up_raw_woocommerce_price( $price ){
        return ceil( $price );
    }
    

    代码进入您的活动子主题(或活动主题)的functions.php 文件中。

    请注意,所有 Woocommerce 价格格式化函数都将使用我们第一个挂钩函数中的四舍五入价格……

    2) 在 WooCommerce 中格式化显示的价格。

    WooCommerce 在任何地方都使用the function wc_price() 来格式化 WooCommerce 设置中定义的价格。

    因此,如果您需要格式化任何原始价格,您将使用该格式化函数,如下例所示:

    // Get the WC_Product Object instance from the product ID
    $product = wc_get_product ( $product_id );
    
    // Get the product active price for display
    $price_to_display = wc_get_price_to_display( $product );
    
    // Format the product active price
    $price_html = wc_price( $price_to_display );
    
    // Output
    echo $price_html
    

    或者同样的事情,使用 WC_Product 内置方法 get_price_html() 更紧凑:

    // Get the WC_Product Object instance from the product ID
    $product = wc_get_product ( $product_id );
    
    // Display the formatted product price
    echo $product->get_price_html();
    

    【讨论】:

    • 嗨@LoicTheAztec,非常感谢您的回答。我尝试添加代码的第一部分: add_filter( 'raw_woocommerce_price', 'round_up_raw_woocommerce_price' ) function round_up_raw_woocommerce_price( $price ){ return ceil( $price );但我遇到了问题,网站崩溃了。我已经注意到在functions.php文件的末尾没有?>。但是我认为问题是由我放置代码的位置引起的。文件末尾有两个“if”函数,我认为代码应该放在这两个部分之前。
    猜你喜欢
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多