首页 > 解决方案 > 如何在 WooCommerce 中四舍五入价格?

问题描述

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

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

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

如前所述,我想将所有价格汇总。

有没有办法这样做?

标签: phpwordpresswoocommerceproductprice

解决方案


您无法真正在全球范围内汇总所有实际计算价格,例如税费、运费、折扣、总计和其他第三方插件计算的价格。四舍五入计算的价格需要逐个进行......</p>

您只能在全球范围内对所有“显示”格式的价格进行四舍五入,保留 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 价格格式化函数都将使用我们第一个挂钩函数中的四舍五入价格……</p>

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

WooCommerce 在任何地方都使用该功能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();

推荐阅读