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' );
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)