You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅对带指定属性的WooCommerce产品设置价格四舍五入?

仅对特定属性产品应用WooCommerce价格四舍五入的实现方法

完全可行,只需在原代码基础上添加产品属性判断逻辑即可,具体实现步骤如下:

  1. 调整钩子参数传递:woocommerce_get_price钩子支持传递产品对象作为第二个参数,需要修改add_filter调用,明确指定接收2个参数。
  2. 添加属性判断逻辑:在回调函数中获取当前产品的目标属性,仅当产品拥有该属性时才执行价格四舍五入操作。

修改后的完整代码:

add_filter( 'woocommerce_get_price', 'custom_calculated_total', 10, 2 );
function custom_calculated_total( $total, $product ) {
    // 替换为你的目标属性Slug(在产品属性设置中查看)
    $target_attr_slug = 'your_attribute_slug';
    
    // 获取产品的该属性值
    $attr_value = $product->get_attribute( $target_attr_slug );
    
    // 仅当产品拥有该属性(值不为空)时,执行价格四舍五入
    if ( ! empty( $attr_value ) ) {
        $total = round( $total, -2 );
    }
    
    return $total;
}

补充说明:

  • 获取属性Slug:进入WooCommerce后台 → 产品 → 属性,找到目标属性,查看其「Slug」字段内容,替换代码中的your_attribute_slug即可。
  • 针对特定属性值:如果需要仅对属性为某个特定值的产品生效,可将判断条件修改为:
    if ( $attr_value === 'your_target_value' ) {
        $total = round( $total, -2 );
    }
    
  • 兼容可变产品:该代码对简单产品和可变产品的子变体均有效,$product会自动指向当前展示的产品/变体对象。

内容的提问来源于stack exchange,提问作者Gavranche

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:43:11