Redirect an admin user role on login with login redirect
You can redirect a user based on their WordPress role with the login_redirect filter.
add_filter( 'login_redirect', 'themeprefix_login_redirect', 10, 3 );
/**
* Redirect user after successful login.
*
* @param string $redirect_to URL to redirect to.
* @param string $request URL the user is coming from.
* @param object $user Logged user's data.
* @return string
*/
function themeprefix_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 default place
return $redirect_to;
} else {
return home_url();
}
} else {
return $redirect_to;
}
}
In the above any admin users to go wp-admin on login every other role goes to the site home URL.
add_filter( 'login_redirect', 'themeprefix_login_redirect', 10, 3 );
/**
* Redirect user after successful login.
*
* @param string $redirect_to URL to redirect to.
* @param string $request URL the user is coming from.
* @param object $user Logged user's data.
* @return string
*/
function themeprefix_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_to = '/wp-admin/'; // Your redirect URL
}
}
return $redirect_to;
}
In the amended code above, any admin is forced to wp-admin as the $redirect_to variable is reset.
In an update to this post – here is an alternative option to redirect based on a certain role using the action wp_login.
add_action( 'wp_login', 'prefix_login_redirect_based_on_roles', 10, 2 );
/**
* Redirect Shop Manager to WC Orders
* @link https://stackoverflow.com/questions/30124931/how-to-redirect-a-user-with-specific-role-to-a-specific-page-after-login-in-wo
*/
function prefix_login_redirect_based_on_roles( $user_login, $user ) {
if( in_array( 'shop_manager',$user->roles ) ){
exit( wp_redirect('/wp-admin/edit.php?post_type=shop_order' ) );
}
}
So in the code above the role of ‘shop_manager’ gets redirected to the WooCommerce Orders screen, change it to meet our needs.