如何实现WooCommerce产品价格十位取整(个位自动归零)?
价格十位取整实现方案
核心逻辑:要实现个位固定为0的四舍五入取整,只需在原有取整逻辑上增加「除以10取整后再乘回10」的运算,完全匹配你的转换需求。
先修正你现有代码的2个问题:
- 原代码缺少函数定义的起始行,直接写
return会触发PHP语法错误 - 重复挂载了
raw_woocommerce_price过滤器,属于冗余配置
完整可用代码
add_filter( 'raw_woocommerce_price', 'round_price_to_tens', 10, 1); add_filter( 'woocommerce_get_price_excluding_tax', 'round_price_to_tens', 10, 1 ); add_filter( 'woocommerce_get_price_including_tax', 'round_price_to_tens', 10, 1 ); add_filter( 'woocommerce_tax_round', 'round_price_to_tens', 10, 1); add_filter( 'woocommerce_get_price', 'round_price_to_tens', 10, 1); // 十位取整规则实现 function round_price_to_tens( $price ) { // 价格先除以10做四舍五入,再乘10得到个位为0的整数价格 return round( $price / 10 ) * 10; }
效果验证
完全匹配你给出的转换示例:
- $2398 → $2400
- $5243 → $5240
- $7567 → $7570
- 原始带小数的转换价$3257.2485... → $3260.00
注意:当前挂载的过滤器会同步作用于前台产品展示、购物车、结算页的全链路价格计算。如果只想调整前端展示效果、不改动实际下单的计价金额,仅保留
raw_woocommerce_price和woocommerce_get_price两个过滤器的挂载即可,删除其余挂载项。
内容的提问来源于stack exchange,提问作者Acon。
相关产品推荐
相关产品推荐

