我想知道是否有办法四舍五入 WooCommerce 中的价格,并保留显示 2 位小数(因此价格将以第一位和第二位小数 00 结尾)。
例如:12,54 欧元将四舍五入为 13,00 欧元,145,67 欧元将四舍五入为 146,00 欧元。
我正在使用一个插件来折扣产品价格,即 €39,00 - 20% = €35,10(应该变成 €36,00)。
我想按照之前的解释对所有价格进行四舍五入。
有办法吗?
最佳答案
您无法真正汇总全局所有实际计算的价格,例如税费、运费、折扣、总计和其他第三方插件计算的价格。计算价格需要根据具体情况进行四舍五入……
您只能对所有“显示”格式的价格进行全局舍入,保留两位小数。为此,有两个步骤解释如下:
1) 以下 Hook 函数将对 WooCommerce 中显示的原始价格进行四舍五入:
如有必要,它将通过向上舍入该值来返回下一个最大整数值。
add_filter( 'raw_woocommerce_price', 'round_up_raw_woocommerce_price' )
function round_up_raw_woocommerce_price( $price ){
return ceil( $price );
}
代码位于事件子主题(或事件主题)的functions.php 文件中。
Note that All Woocommerce price formatting functions will use our rounded prices from our first hooked function…
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();
关于php - 如何对 WooCommerce 中的价格进行四舍五入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61836970/