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

请求修改WooCommerce结账后自动登录已有账户的functions.php代码

WooCommerce结账后自动登录已有账户的代码修改方案

现有WooCommerce的functions.php代码可检测结账时的已有账户,但缺少付款完成后自动登录的功能,需修改实现:当已有账户完成结账付款后,自动创建登录会话,让用户以customer角色登录,以便访问受保护页面。

修改后的完整代码

/**
* 检测结账时的已有账户并在付款完成后自动登录
* @param {object} $data 结账表单的HTTP POST数据
*
* @return $data
*/
add_filter( 'woocommerce_checkout_posted_data', 'filter_woocommerce_checkout_posted_data', 10, 1);
function filter_woocommerce_checkout_posted_data( $data) {
    // 若用户已登录,直接返回数据走正常结账流程
    if ( is_user_logged_in()) {
        return $data;
    }

    // 仅在未登录且处于结账页面时执行
    if ( !is_user_logged_in() && is_checkout()) {
        $user = get_user_by('email', $data['billing_email']);
        if ( !empty($user->ID) ) {
            wp_set_current_user($user->ID);
            $data['createaccount'] = 0; // 取消创建新用户的标记
        } else {
            $data['createaccount'] = 1; // 标记需要创建新用户
        }
    }
    return $data; // 补充原代码遗漏的返回值
}

/**
* 付款完成后自动登录已有账户
* @param {int} $order_id 订单ID
*/
add_action( 'woocommerce_payment_complete', 'auto_login_existing_user_after_checkout', 10, 1 );
function auto_login_existing_user_after_checkout( $order_id ) {
    // 若用户已登录,无需处理
    if ( is_user_logged_in() ) {
        return;
    }

    $order = wc_get_order( $order_id );
    if ( !$order ) {
        return;
    }

    // 获取订单对应的用户邮箱
    $billing_email = $order->get_billing_email();
    $user = get_user_by( 'email', $billing_email );

    // 验证用户存在且为customer角色
    if ( $user && in_array( 'customer', $user->roles ) ) {
        // 创建用户登录会话
        wp_set_auth_cookie( $user->ID, true );
        wp_set_current_user( $user->ID );
        do_action( 'wp_login', $user->user_login, $user );
    }
}

关键改动说明

  1. 补充原代码遗漏的return $data;,确保过滤器正常返回数据
  2. 添加woocommerce_payment_complete动作钩子:该钩子在订单付款完成后触发,是实现自动登录的合适时机
  3. 自动登录函数逻辑:
    • 跳过已登录用户的处理
    • 通过订单邮箱匹配已有用户
    • 确认用户为customer角色后,创建持久登录会话并触发标准登录动作,保证登录流程完整

注意事项

  • 请将代码添加到主题或子主题的functions.php文件中,避免主题更新丢失代码
  • 测试前请做好网站备份,避免出现意外问题
  • 此代码仅针对已有账户生效,新创建的账户仍会按WooCommerce默认逻辑发送登录凭证邮件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 14:48:25