您无法真正汇总全球所有真实计算价格,例如税金、运费、折扣、总计和其他第三方插件计算的价格。四舍五入计算的价格需要逐案进行......
您只能在全球范围内对所有“显示”格式的价格进行四舍五入,保留 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();