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

WooCommerce账单与收货地址不匹配时将订单设为暂停的代码排查

原代码错误点
  • 变量未定义:$user_id没有提前赋值就直接传入WC_Customer构造方法,会直接抛出报错,且游客下单场景下没有对应用户账户,这套读取用户账户地址的逻辑本身就不适用。
  • 赋值语法错误:所有地址字段的赋值全部误用了比较运算符==,而非赋值运算符=,导致所有存储地址的变量实际为null,后续的比对逻辑完全失效。
  • 比对逻辑错误:你需要比对的是当前订单提交的账单地址和收货地址,而不是用户账户里预先存储的地址,用户下单时可以临时修改地址,且游客下单没有账户地址,原逻辑完全不符合需求场景。
  • 触发钩子不稳定:使用woocommerce_thankyou作为触发时机,存在用户支付后未跳转感谢页、重复刷新感谢页的漏触发/重复触发问题。
修正后可直接使用的代码
add_action( 'woocommerce_checkout_order_processed', 'auto_hold_order_if_billing_shipping_not_match', 10, 1 );
function auto_hold_order_if_billing_shipping_not_match( $order_id ) {
    if ( ! $order_id ) {
        return;
    }
    $order = wc_get_order( $order_id );
    if ( ! $order ) {
        return;
    }

    // 直接从当前订单读取账单地址
    $billing = [
        'first_name' => $order->get_billing_first_name(),
        'last_name'  => $order->get_billing_last_name(),
        'company'    => $order->get_billing_company(),
        'address_1'  => $order->get_billing_address_1(),
        'address_2'  => $order->get_billing_address_2(),
        'city'       => $order->get_billing_city(),
        'state'      => $order->get_billing_state(),
        'postcode'   => $order->get_billing_postcode(),
        'country'    => $order->get_billing_country()
    ];

    // 直接从当前订单读取收货地址
    $shipping = [
        'first_name' => $order->get_shipping_first_name(),
        'last_name'  => $order->get_shipping_last_name(),
        'company'    => $order->get_shipping_company(),
        'address_1'  => $order->get_shipping_address_1(),
        'address_2'  => $order->get_shipping_address_2(),
        'city'       => $order->get_shipping_city(),
        'state'      => $order->get_shipping_state(),
        'postcode'   => $order->get_shipping_postcode(),
        'country'    => $order->get_shipping_country()
    ];

    // 地址比对,任意字段不匹配则设为暂停
    if ( $billing !== $shipping ) {
        $order->add_order_note( __('账单地址与收货地址不匹配,订单自动暂停') );
        $order->update_status( 'on-hold' );
        $order->save();
    }
}

补充说明:如果需要忽略地址大小写、空白字符的差异,可以在比对前对每个字段做trim()、strtolower()格式化处理即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 01:54:03