1

When a user login, we can easily change the redirect URL (see this, this, or this), but if the user goes to /wp-login.php, they will be redirected to the dashboard if they are already logged in.

My question is, when the user visits /wp-login.php and is already logged in, how can I redirect them to a custom URL?

2 Answers 2

3

The best way to figure out what's happening for a problem like this is to go to the source. Literally.

Take a look in wp-login.php and look for an action that fires before any HTML rendering happens. The hook you're looking for is login_init. Add a callback to it, check if the user is logged in and redirect them if so.

The only other snag here is that wp-login.php also handles logging out. So you need to check the global $action variable to make sure a logout isn't in progress.

add_action('login_init', 'wpse187831_redir_loggedin');
function wpse187831_redir_loggedin()
{
    global $action;

    if ('logout' === $action || !is_user_logged_in()) {
        return;
    }

    wp_redirect(apply_filters(
        'wpse187831_loggedin_redirect',
        current_user_can('read') ? admin_url() : home_url(),
        wp_get_current_user()
    ), 302);
    exit;
}

There's a bit of extra stuff there:

  • A call to apply_filters so other plugins can hook in and modify my redirect if they like. This filter gets the redirect itself as well as the current user.
  • There's a check to see if the current user can actually access the admin area before redirecting them there.

Here's that little snippet as a plugin.

2
  • Ah unfortunately, it appears this solution is preventing logout. Try clicking on default logout link on admin-bar or one generated with wp_logout_url() -- any way to escape if user is trying to logout?
    – Christine Cooper
    Commented May 10, 2015 at 17:18
  • 1
    Answer and plugin updated! Commented May 11, 2015 at 0:48
2

You can check if the current page is login or not using $pagenow global variable and the wp_redirect() to custom URL within the condition is_user_logged_in

function redirect_logged_in_user() 
{
    if( is_user_logged_in ) {
      wp_redirect('http://customurl');
    }
}

global $pagenow;
if( $pagenow == 'wp-login.php')     
redirect_logged_in_user();
2
  • Very interesting approach, thank you for the answer. Although, when considering performance, is there any way to achieve this by hooking into something that only runs when user visits the wp-login.php page?
    – Christine Cooper
    Commented May 9, 2015 at 18:25
  • I couldn't find any built in function for finding login page, hence I had to use a global variable. Let me know if that works.
    – m4n0
    Commented May 10, 2015 at 2:23

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.