0

In my plugin I try to login a user and redirect them to a specific page, but when I redirect the user, they are not logged in :-/

I have tried multiple variations of code that looks like this:

$wp_user = get_user_by( 'email', '[email protected]');
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;
}

How can I programmatically login the user and redirect them to a specific page?

3 Answers 3

0

Try change this:

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

To:

wp_safe_redirect($redirect_to )
exit;
1
  • That would only make a difference if wp_safe_redirect was cancelled by a filter though, and if it was then you'd just exit. (These are both acceptable patterns in the documentation.)
    – Rup
    Oct 28, 2020 at 22:59
0

Are you trying to log them in or redirect them after they login themselves?

If the later, use the login_redirect hook -

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

2
  • I'd guess log them in, judging by the code in the question - wp_set_auth_cookie etc.
    – Rup
    Oct 29, 2020 at 10:16
  • @Rup good point
    – omni
    Oct 29, 2020 at 10:21
0

I used the following code to do that in order to let clients see a site that I don't want shown publicly. For my use case, I just need it to go to the url they typed in. You can put whatever you want where I added the comment.

I had to add the '?noredirect=true' part because otherwise you end up getting a multiple redirect issue.

I hope this is helpful.

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');
2
  • I think template_redirect might be a better hook. The init hook runs on both the front-end and admin. You also wouldn't need to worry about checking for noredirect.
    – Howdy_McGee
    Oct 30, 2020 at 3:14
  • Good point. Thanks @Howdy_McGee. Nov 11, 2020 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.