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