How redirect a user after login based on their WordPress role

How to redirect a user after login based on their WordPress role.
How to redirect users who log in to your site to another URL based on their role. Just add this WordPress code snippet to your theme’s functions.php file.
The function checks for the user role id and redirects to the defined page by using wp_redirect function.

function ns_redirect_user_on_role() {
  //retrieve current user info 
  global $current_user;
  get_currentuserinfo();

  //If login user role is Subscriber
  if ( $current_user>user_level == 0 ){
    wp_redirect( home_url() ); exit;
  }

  //If login user role is Contributor
  else if ( $current_user>user_level > 1 ){
    wp_redirect( home_url() ); exit;
  }

  //If login user role is Editor
  else if ( $current_user->user_level > 8 ){
    wp_redirect( home_url() ); exit;
  }

  // For other rolse 
  else{
  $redirect_to = 'http://google.com/';
    return $redirect_to;
  }
  
}
add_action( 'admin_init','ns_redirect_user_on_role' );

 

How redirect a user after login based on their WordPress role

Read more about WordPress Roles and Capabilities here.

Thank you for seeing my code snippet and feel free to share and comment :).Do you have any interesting changes to this snippet that you know or some other cool code snippets that you’d like to share? Let everyone know in the comments what cool tricks you’ve come up with or you can let me know by contacting me (here)

ABOUT AUTHOR

Nuno

I am a Freelance Web Developer and WordPress Expert based in London with a wealth of website development and support experience. I am great at problem solving and developing quick solutions.

  • LET'S TALK!

    Fill in the form below to make an enquiry or find my contact details on my contact page.

  • This form collects your name and email address so that I can respond to the enquiry(ies) that you submit via this website. Please check my privacy policy for the full story on how I use, protect and manage your submitted data.