如何在插件中登录用户并重定向到页面?

时间:2020-10-28 作者:Martin Andersen

在我的插件中,我尝试登录用户并将其重定向到特定页面,但当我重定向用户时,他们没有登录:-/

我尝试了多种类似以下的代码变体:

$wp_user = get_user_by( \'email\', \'johndoe@example.com\');
wp_clear_auth_cookie();
do_action(\'wp_login\', $wp_user->user_login, $wp_user);
wp_set_current_user($wp_user->ID);
wp_set_auth_cookie($wp_user->ID, true);
$redirect_to = \'/\' . $redirectUrl;

if ( wp_safe_redirect($redirect_to ) ) {
    exit;
}

如何以编程方式登录用户并将其重定向到特定页面?

3 个回复
SO网友:tagformat.com

尝试更改此选项:

if ( wp_safe_redirect($redirect_to ) ) {
    exit;
}
收件人:

wp_safe_redirect($redirect_to )
exit;

SO网友:omni

您是否尝试在他们自己登录后登录或重定向他们?

如果是后者,请使用login\\u重定向挂钩-

https://developer.wordpress.org/ref.../hooks/login_redirect/

SO网友:John Deaton

为了让客户看到我不想公开显示的站点,我使用了以下代码。对于我的用例,我只需要它转到他们键入的url。你可以把你想要的任何东西放在我添加评论的地方。

我必须添加“?noredirect=true“部分原因是,否则最终会出现多重重定向问题。

我希望这是有益的。

function dwd_redirect_logged_out() {
    if (isset($_POST[\'wp-submit\'])) {}
    else {
        if ( !is_user_logged_in() ) {
            if (!isset($_GET[\'noredirect\'])) {
                wp_redirect(wp_login_url() . \'?noredirect=true\'); 
                exit;
            }
        }
        else {
            // PUT A wp_redirect() statement here to go somewhere else
        }
    }
}
add_action(\'init\', \'dwd_redirect_logged_out\');