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.