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?

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.

  • 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 May 10 '15 at 17:18
  • 1
    Answer and plugin updated! – chrisguitarguy May 11 '15 at 0:48
1

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();
  • 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 May 9 '15 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. – Manoj Kumar May 10 '15 at 2:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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