How to redirect specific user roles after successful login

We have already shown you how to redirect users after their logout. But what if you need to redirect users to their login pages? In this article, we will show you a code which you can easily modify and control where a certain user lands after successful login to your WordPress powered website.

By default, WordPress will take every user to the dashboard and that might be a problem for some of you. Maybe you want to keep your admins and authors on the backend while you want to lead your other users directly on your homepage or maybe onto another frontend page you have created specifically for them.

To redirect users based on their roles, follow next steps:

  1. Open functions.php file
  2. Copy and paste the following code:
  3. function my_login_redirect( $url, $request, $user ){
    if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
    if( $user->has_cap( 'administrator') or $user->has_cap( 'author')) {
    $url = admin_url();
    } else {
    $url = home_url('/custom-page /');
    }
    }
    return $url;
    }
    add_filter('login_redirect', 'my_login_redirect', 10, 3 );
  4. Save changes

The code shown above will leave the admins right where they need to be – the admin panel, while all other users will be taken to a custom page.

You can easily change URLs by changing the $url variable on the 4th and the 6th line and therefore lead your users to any posts/pages you have created for them.

If you want to control user roles, you can do that easily on the third line of the code. In the above-given example, we have left admins and authors on the admin panel. If you want only admins there, simply remove the authors from the picture:

if( $user->has_cap( 'administrator' ) ) {

Instead of removing authors, you can add other roles as well; it is up to you to decide who will end up on which page.

That’s it. With this code, you don’t need any plugin to control the redirects after a user logs in. If you’re still not into changing the code, see how to redirect users after login with a plugin.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *