php - 如何在 WooCommerce 中四舍五入价格?
问题描述
我想知道是否有办法在 WooCommerce 中对价格进行四舍五入,保持显示 2 位小数(因此价格将以第一个和第二个小数结尾,00)。
例如:12.54 欧元将四舍五入为 13.00 欧元,145.67 欧元将四舍五入为 146.00 欧元。
我正在使用一个插件来打折产品价格,即 39,00 欧元 - 20% = 35,10 欧元(应该变成 36,00 欧元)。
如前所述,我想将所有价格汇总。
有没有办法这样做?
解决方案
您无法真正在全球范围内汇总所有实际计算价格,例如税费、运费、折扣、总计和其他第三方插件计算的价格。四舍五入计算的价格需要逐个进行......</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();
推荐阅读
- powershell - Powershell脚本如何处理直接传递给模块的参数
- python - 热绘制曲线并将其转换为 numpy
- c# - 试图制作“火与冰的舞蹈”并且遇到矢量问题
- angular - 嗨,我在 Angular 中使用 ngx-microsoft-bot-framework。我如何将 QNA Maker 服务添加到 TS 文件中
- docker - 任务 ':website:buildDockerImage' 执行失败。使用 Apache Beam 的 gradlew 构建
- javascript - Vuex getter 未定义但状态出现在控制台中
- r - R Shiny 如何选择输入表单数据框列(反应式)
- python - 使用python将文件上传到s3时更改元数据
- node.js - 在 GET 请求中发送 base64 数据的问题
- parameters - SAS宏参数中的换行符丢失