php - 如何对 WooCommerce 中的价格进行四舍五入?

标签 php wordpress woocommerce product price

我想知道是否有办法四舍五入 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/

相关文章:

php - 如何将复选框数组保存到数据库中?

php - 用 JavaScript 编写的 Cookie 在 PHP 中仅显示为整数

php - 在 Woocommerce 订阅中以编程方式创建订单

php - 更改 WooCommerce 3+ 中现有产品的产品类型

css - 奇怪的 CSS 覆盖类问题

php - Bootstrap 模式中的表单不会将 PHP 值发布到另一个页面

php - 在php中将长度超过16位的int转换为字符串

javascript - WordPress 中的 masonry

php - 将 WooCommerce 0 销售价格替换为自定义文本,并保留常规价格删除线

php - 如何在 WordPress 中搜索我的数据库以获取自定义字段的所有选项?