This example redirects admins to the dashboard and other users to the homepage. Make sure you use add_filter outside of is_admin() , since that function is not available when the filter is called.
/**
* 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 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 default place
return $redirect_to;
} else {
return home_url();
}
} else {
return $redirect_to;
}
}
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );
In the example, ‘filter_function_name’ is the function WordPress should call during the login process. Note that filter_function_name should be unique function name. It cannot match any other function name already declared.
The $current_user global may not be available at the time this filter is run. So you should use the $user global or the $user parameter passed to this filter.
Examples
This example redirects admins to the dashboard and other users to the homepage. Make sure you use add_filter outside of is_admin() , since that function is not available when the filter is called.
Notes
You can register the login_redirect filter to use all 3 parameters like this:
In the example, ‘filter_function_name’ is the function WordPress should call during the login process. Note that filter_function_name should be unique function name. It cannot match any other function name already declared.
The $current_user global may not be available at the time this filter is run. So you should use the $user global or the $user parameter passed to this filter.
Example Migrated from Codex:
Redirect all logins to the homepage with an anonymous function (php 5.3+).
Thanks WP Scholar : https://wpscholar.com/blog/wordpress-user-login-redirect/ :D
$user->has_cap()to check a role is discouraged as it may produce unreliable results.