WordPress Login Redirection for Admins and Users with Custom Roles

Explore our WordPress category, where you’ll find loads of helpful articles and tutorials for everyone, whether you’re just starting out or a pro developer. Learn about different WordPress themes and plugins that can be applied in various projects according to their specific requirements.

WordPress filter function that customizes the login redirect behavior based on the user’s role.this code ensures that when users log in, administrators are redirected to the WordPress dashboard, while non-administrators are redirected to the home page.
function my_login_redirect( $redirect_to, $request, $user ) {
// Is there a user to check?
if ( isset( $user->roles ) && is_array( $user->roles ) ) {
// Check for admins
if ( in_array( ‘administrator’, $user->roles ) ) {
// Redirect them to the WordPress dashboard
return admin_url();
} else {
// Redirect non-admin users to the home page
return home_url();
}
} else {
// If there’s no user information, return the original redirect URL
return $redirect_to;
}
}
add_filter( ‘login_redirect’, ‘my_login_redirect’, 10, 3 );
The my_login_redirect function is defined, which takes three parameters: $redirect_to (the redirect URL), $request (the requested redirect), and $user (the user object).
It checks if the $user object has roles and if it is an array. If so, it proceeds to check the user’s role.
If the user is an administrator (‘administrator‘ role), it redirects them to the WordPress dashboard using admin_url().
If the user is not an administrator, it redirects them to the home page using home_url().
If there is no user information available, it returns the original redirect URL.
The add_filter function is then used to hook this custom redirect function into the WordPress login redirect process.