自动登录挂钩需要刷新页面

时间:2013-01-31 作者:Justin Helgerson

我有一个简单的自动登录挂钩,如下所示:

function auto_login() {
    if (!is_user_logged_in()) {
        //Removed some code for brevity.

        $user = get_userdatabylogin($domainName);

        if ($user != null) {
            //Set the auth cookie.
            wp_set_auth_cookie($user->ID, false, null);
            //Set the current user (this will also set WP objects at the global level)
            wp_set_current_user($user->ID);
        }
    }
}
add_action(\'init\', \'auto_login\');
这段代码确实有效,但为了在页面顶部获得管理栏,需要刷新页面。这让我觉得我没有在Wordpress页面生命周期中尽早填充一些全局对象。

我应该在其他地方调用此方法吗init?

2 个回复
最合适的回答,由SO网友:david.binda 整理而成

也许现在开始使用init已经太迟了。请尝试设置\\u current\\u user或更早的挂钩。列表如下:https://codex.wordpress.org/Plugin_API/Action_Reference

SO网友:joshwhatk

我发现用户可以自动登录template_redirect 并使用成功设置wp_redirect(\'yoururl\'), 本质上,它使用cookie重定向回页面,而不是重新加载页面。

示例:

function auto_login() {
    // if statements go here...

    $user_id = \'some_user_id\';

    wp_set_auth_cookie($user_id);
    wp_set_current_user($user_id);

    wp_redirect(home_url());
    exit;
}
add_action(\'template_redirect\', \'auto_login\');

结束

相关推荐

Security updates to 3.3.2

我知道所有的安全更新都很重要,但从1到10的范围来看,从3.1.3升级到3.3.2有多重要。我有一些网站需要升级,但主机将我锁定在一个旧版本的php中,限制我使用3.1.3。我目前正在运行php的5.2.3版本。谢谢Bart