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

如何在特定产品ID加入购物车时设置WooCommerce指定分类商品价格

解决WooCommerce中特定商品触发指定分类商品免费的问题

看来你之前的代码没做好精准的分类判断,才会把所有商品价格都清零了。别慌,我来给你写一个完全符合需求的实现代码:

核心逻辑拆解

  1. 先检测购物车中是否存在目标商品(Product 2)
  2. 确认存在后,遍历购物车所有商品,仅将属于「Books」分类的商品价格设为0
  3. 加入钩子重复触发防护,避免WooCommerce计算异常

完整可运行代码

add_action( 'woocommerce_before_calculate_totals', 'apply_books_free_on_specific_product', 10, 1 );
function apply_books_free_on_specific_product( $cart ) {
    // 防止钩子重复执行导致的计算混乱
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) {
        return;
    }

    // 替换为你的Product 2的实际ID(在商品列表可查看)
    $target_product_id = 2;
    // 替换为你的图书分类的别名(在产品分类设置中查看),也可以用分类ID,比如改成5
    $books_category_slug = 'books';

    $has_target_product = false;

    // 检查购物车是否包含Product 2
    foreach ( $cart->get_cart() as $cart_item ) {
        // 同时匹配主商品ID和变体ID
        if ( $cart_item['product_id'] == $target_product_id || $cart_item['variation_id'] == $target_product_id ) {
            $has_target_product = true;
            break;
        }
    }

    // 若存在目标商品,处理图书分类商品价格
    if ( $has_target_product ) {
        foreach ( $cart->get_cart() as $cart_item ) {
            $product = $cart_item['data'];
            // 验证当前商品是否属于Books分类
            if ( has_term( $books_category_slug, 'product_cat', $product->get_id() ) ) {
                // 设置商品价格为0
                $product->set_price( 0 );
                // 兼容可变商品,同步修改所有变体价格
                if ( $product->is_type( 'variable' ) ) {
                    foreach ( $product->get_children() as $variation_id ) {
                        $variation = wc_get_product( $variation_id );
                        $variation->set_price( 0 );
                        $variation->save();
                    }
                }
            }
        }
    }
}

关键细节说明

  • 用did_action限制钩子执行次数,避免WooCommerce重复调用时出现价格异常
  • 你需要手动替换$target_product_id和$books_category_slug为你店铺的实际值
  • 同时兼容简单商品和可变商品,确保所有图书分类下的商品都能被正确设为免费
  • 只有当购物车中存在Product 2时,才会触发免费逻辑,其他场景商品价格保持正常

使用建议

把这段代码添加到主题的functions.php文件中,或者使用专门的自定义代码插件(比如Code Snippets)来管理,这样能避免主题更新导致代码丢失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:13:18