How redirect a user after login based on their WordPress role

 In Functions, Redirects, Security, Wordpress Admin

How redirect a user after login based on their WordPress role.

How to redirect users who login 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 define 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 fell 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 contact me (here)

Learn how to build Custom WordPress Registration Form with Bootstrap @ https://www.wp-code.uk – Nuno Sarmento

Recommended Posts

Start typing and press Enter to search

Let's work together

I'd love to work with you! Please fill out my project form to tell me more about your project/work. I reply to all enquiries within 48 hours.

Availability

  • June - Booked
  • July - Booked
  • August - Limited

Rates

  • My day rate is £300.
  • I can provide a fixed price for your work.
  • Projects start at around £2,000.

Header Enquiry Form

  • This form collects your name, email address and telephone number 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.