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

WooCommerce购物车赠品功能异常:赠品仅可添加一次如何修复?

问题分析

你代码存在4个核心错误,直接导致功能不符合预期:

  • 加赠品逻辑的外层判断限制了首次加购的触发,且全局校验赠品是否存在,自然只会加一次赠品
  • 移除函数中$is_allowedPrd未初始化,触发PHP警告导致逻辑失效
  • 移除赠品时没有遍历获取所有赠品的购物车key,仅能操作最后一个遍历到的商品,无法正确删除赠品
  • 没有考虑多份主商品对应多份赠品的匹配逻辑,你当前的逻辑不管加几个主商品,最多只会加一套赠品
修正后的完整代码
/* 给指定商品加赠品 */
function gift_add_product_to_cart() {
  $free_product_ids = array(20070, 39039); // 赠品的商品ID
  $allowed_product_ids = array(38162, 38157); // 可以触发赠品的主商品ID
  $allowed_count = 0; // 符合条件的主商品数量
  $existing_free_gifts = array(); // 已存在的赠品数量统计

  $cart = WC()->cart->get_cart();
  // 先统计购物车内的主商品和赠品数量
  foreach ( $cart as $cart_item_key => $values ) {
    $_product = $values['data'];
    $product_id = $_product->get_id();
    if (in_array($product_id, $free_product_ids) && isset($values['freeDosMas']) && $values['freeDosMas'] == 'yes'){
      if(!isset($existing_free_gifts[$product_id])) $existing_free_gifts[$product_id] = 0;
      $existing_free_gifts[$product_id] += $values['quantity'];
    }
    if (in_array($product_id, $allowed_product_ids)){
      $allowed_count += $values['quantity'];
    }        
  }

  // 按主商品数量补充对应数量的赠品
  if ($allowed_count > 0){
    foreach($free_product_ids as $free_id){
      $current_free_count = isset($existing_free_gifts[$free_id]) ? $existing_free_gifts[$free_id] : 0;
      $need_add = $allowed_count - $current_free_count;
      if($need_add > 0){
        WC()->cart->add_to_cart($free_id, $need_add, NULL, NULL, array('freeDosMas' => 'yes'));
      }
    }
  }
  // 如果没有符合条件的主商品,清空所有赠品
  else {
    foreach ( $cart as $cart_item_key => $values ) {
      if (in_array($values['product_id'], $free_product_ids) && isset($values['freeDosMas']) && $values['freeDosMas'] == 'yes'){
        WC()->cart->remove_cart_item( $cart_item_key );
      }
    }
  }
}
add_action( 'woocommerce_add_to_cart', 'gift_add_product_to_cart', 10, 2 );
add_action( 'woocommerce_cart_item_removed', 'gift_add_product_to_cart', 10, 2 ); // 移除商品后也刷新赠品
add_action( 'woocommerce_cart_item_restored', 'gift_add_product_to_cart', 10, 2 ); // 恢复商品后也刷新赠品
add_action( 'woocommerce_after_cart_item_quantity_update', 'gift_add_product_to_cart', 10, 2 ); // 改商品数量也刷新赠品
优化说明
  • 删掉了原代码的购物车非空判断,不管购物车是不是空都正常统计商品
  • 按主商品的实际购买数量匹配赠品数量,加多少份主商品就同步给多少套赠品
  • 将加赠、移除逻辑整合到同一个函数,所有购物车变动钩子都绑定同一套逻辑,避免了原代码变量未定义、找不到赠品ID的问题
  • 新增数量校验逻辑,修改主商品购买数量时赠品也会同步增减

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:06:06