WordPress自定义自动登录函数无法正常工作的原因及解决方法
问题原因与修复方案
核心原因
代码中的exit;语句是导致问题的关键:
gform_user_registered钩子触发时,Gravity Forms后续还有页面重定向、HTTP响应收尾等流程需要执行。exit会直接终止PHP脚本,导致WordPress无法完整发送包含认证Cookie的响应内容。- 服务器端日志显示“已登录”是因为PHP层面确实完成了用户身份标记,但浏览器没有收到有效的认证Cookie,前端自然无法识别用户已登录状态。
修复方法
1. 移除exit;语句
让Gravity Forms完成后续默认流程,确保认证Cookie被正确发送到浏览器:
// Hook into the Gravity Forms User Registration process add_action('gform_user_registered', 'auto_login_after_registration', 10, 4); function auto_login_after_registration($user_id, $config, $entry, $password) { // Log the user in wp_clear_auth_cookie(); wp_set_current_user($user_id); wp_set_auth_cookie($user_id); // Ensure the global $current_user is set global $current_user; $current_user = get_userdata($user_id); // Debugging: Verify user login status if (is_user_logged_in()) { error_log('User is logged in: ' . $current_user->user_login); } else { error_log('User login failed.'); } }
2. 可选:自定义重定向(若需跳转指定页面)
如果需要在登录后跳转到自定义页面,可添加wp_redirect(),但需注意仅在重定向后使用exit:
// Hook into the Gravity Forms User Registration process add_action('gform_user_registered', 'auto_login_after_registration', 10, 4); function auto_login_after_registration($user_id, $config, $entry, $password) { // Log the user in wp_clear_auth_cookie(); wp_set_current_user($user_id); wp_set_auth_cookie($user_id); // Ensure the global $current_user is set global $current_user; $current_user = get_userdata($user_id); // Debugging: Verify user login status if (is_user_logged_in()) { error_log('User is logged in: ' . $current_user->user_login); } else { error_log('User login failed.'); } // 自定义跳转页面示例 wp_redirect(home_url('/member-dashboard/')); exit; }
说明
移除exit后,Gravity Forms会执行默认的注册完成逻辑(如跳转到预设的感谢页面),此时浏览器已收到认证Cookie,前端的登录/登出按钮状态会自动更新。
内容的提问来源于stack exchange,提问作者Sandaruvan Vijayadasa
相关产品推荐
相关产品推荐

