0

Desired Outcome

I am developing a plugin that should redirect the user away from log in page if they are already logged in.

So if anyone goes to example.com/wp-login.php and they are already logged in, the redirect should kick in.

Current Progress

I am using login_init hook to determine that we are in the log in page and wp_get_current_user() to get the user.

function redirect_logged_in_users() {
   if (is_user_logged_in()) {
     wp_redirect($destination);
  }
}

add_action('login_init', 'redirect_logged_in_users');

The Problem

This works well in any other page using some other hook, like init, but whenever I try this with login_init the wp_get_current_user() returns an empty user as if no one is logged in.

I know that there's a user logged in.

Additional Context

I am not a WordPress dev and I am almost sure that I am doing something in a non-WordPress way. Happy to take any other approach which helps to achieve the goal.

1 Answer 1

1

You have a chicken and egg problem going. login_init is called PRIOR to the user actually logged in. It just indicates with the login page has been displayed. (https://developer.wordpress.org/reference/hooks/login_init/)

The hook should be: wp_login. This fires after a user has successfully logged-in.
https://developer.wordpress.org/reference/hooks/wp_login/

add_action('wp_login', 'redirect_logged_in_users');
1
  • Thanks for your answer, just tried it. It seems that "wp_login" fires only after the user has logged in by entering username and password. However, in my case, I need to know if they are authenticated (or logged in) before the log in page loads.
    – ekd
    Commented Mar 12, 2019 at 10:22

Your Answer

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

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