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

WooCommerce强制取消订单备注功能异常:无备注订单仍被取消求助

问题排查与修复方案

核心问题分析

你的代码存在几个关键缺陷导致功能失效:

  • 备注范围限制:get_customer_order_notes()仅获取客户添加的备注,团队成员(管理员)添加的备注不会被检测到,导致即使合规备注存在也会被误判。
  • 原状态获取逻辑错误:依赖_status_previous自定义元字段,但WooCommerce默认不存储该字段,导致$previous_status为空,无法执行状态回滚。
  • 字符串匹配不精确:代码检查的是order got cancelled because,但需求要求备注以order got cancelled because.(带末尾的点)开头,匹配条件不匹配。
  • 大小写敏感:未处理大小写差异,成员输入大写开头的备注会被忽略。

修复后的代码

add_action('woocommerce_order_status_changed', 'check_order_status_change', 10, 4);
function check_order_status_change($order_id, $from_status, $to_status, $order) {
    // 检查是否要改为取消状态
    if ($to_status === 'cancelled') {
        // 获取所有订单备注(含管理员、客户)
        $order_notes = $order->get_order_notes();
        $cancelled_note_exists = false;
        $required_prefix = 'order got cancelled because.';

        // 遍历备注,忽略大小写检查前缀匹配
        foreach ($order_notes as $note) {
            if (strpos(strtolower($note->content), strtolower($required_prefix)) === 0) {
                $cancelled_note_exists = true;
                break;
            }
        }

        // 未找到合规备注,回滚至原状态
        if (!$cancelled_note_exists) {
            $order->set_status($from_status);
            $order->save();

            // 添加管理员通知备注
            $order->add_order_note(
                __('订单状态已回滚至' . $from_status . ',原因:未提供符合要求的取消备注(需以"order got cancelled because."开头)。', 'woocommerce'),
                true
            );
        }
    }
}

关键修复点说明

  • 扩展备注检测范围:用get_order_notes()替代get_customer_order_notes(),确保能检测到所有角色添加的备注。
  • 直接使用原状态参数:利用钩子自带的$from_status参数获取原状态,无需依赖自定义元字段,避免空值导致的回滚失败。
  • 精确匹配前缀:修正匹配字符串为带点的order got cancelled because.,同时通过strtolower()实现大小写不敏感检查,提升兼容性。
  • 优化提示文案:调整备注文案为中文,更符合团队使用习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:57:44