Redirect specific user roles after login in WordPress

Depending on who's logging in to your WordPress site you might want to direct them to a different page. For example, you might want administrators to access the standard wp-admin area, but direct subscribers or custom role types to a bespoke page. This post introduces a few different options that you can do programatically without installing any third-party plugins.

Re-direct specifc user roles

The following code will check if a custom role of 'member' is assigned to the user logging in, if so it will redirect them to a custom 'members' page, the code should be placed in your functions.php file:

function members_login_redirect($redirect_to, $request, $user)
{
    $role = 'member';
    if(in_array($role, $user->roles))
    {
        return '/members';
    }
}

add_filter( 'login_redirect', 'members_login_redirect', 10, 3);

Re-direct non administrators

The following code will check if the user has the administrator role, if they do they will be directed to the administator url (found using the admin_url function), if not they will directed to a custom members page.

function users_login_redirect($redirect_to, $request, $user)
{
    if(in_array('administrator', $user->roles))
    {
        return admin_url();
    } 
    else
    {
        return '/members';
    }
}

add_filter( 'login_redirect', 'users_login_redirect', 10, 3);

The above code is better for readability, but you could reduce the lines of code down by using the following:

function users_login_redirect($redirect_to, $request, $user)
{
    return (in_array('administrator', $user->roles)) ? admin_url() : '/members';
}

add_filter( 'login_redirect', 'users_login_redirect', 10, 3);

Sign Up
comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.