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

woocommerce_cart_calculate_fees在结算页触发两次 提示重复如何解决?

问题原因

woocommerce_cart_calculate_fees 钩子在WooCommerce结算页默认会被触发2次,分别用于购物车金额计算、运费和税费校验逻辑,所以你的函数会执行两次,自然就重复添加了两次相同的通知。你之前写的for ($i=0;$i>1;$i++)限制逻辑本身条件不成立,$i初始值为0时$i>1为假,循环完全不会运行,因此起不到限制作用。

修复方案

在函数内新增静态变量作为执行标记,同一次页面请求中函数多次调用时会保留静态变量的值,确保通知仅添加一次,修改后的代码如下:

function add_custom_discount_2nd_at_50( $cart ){
  // 静态变量存储通知添加状态,同次请求多次调用函数时该值会保留
  static $notice_added = false;
  // 已添加过通知直接跳过后续逻辑
  if ($notice_added) return;

  $item_count = WC()->cart->get_cart_contents_count();
  // $item_count = sizeof($package['contents']); -- 指商品种类总数,不统计单款商品的购买数量

  $totalnum = 3;
  if ( $item_count < $totalnum ) {
      $itemdiff = $totalnum - $item_count;
      // 适配多语言的正确写法,避免拼接变量导致翻译失效
      $notice = sprintf( __("Add %s more products for Free Shipping.", 'xlate'), $itemdiff );
      // 如果需要显示中文提示,替换为下面的代码即可
      // $notice = sprintf( __("再添加%s件商品即可享受免邮优惠", 'xlate'), $itemdiff );
  }

  if ( isset($notice) ) {
      wc_add_notice( $notice, 'notice' );
      // 标记通知已添加,后续函数调用不再重复执行
      $notice_added = true;
  }

}
add_action('woocommerce_cart_calculate_fees', 'add_custom_discount_2nd_at_50', 10, 1 );

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:39:03