Custom login redirect to referring and custom URL based on role.


I’m wondering if anyone might be able to help me out or point me in the right direction.

I’ve been trying for a few days here to come up with something that would redirect users upon login based on roles. Basically, I’d like to redirect everyone that is not an administrator to the referring URL and administrator to a custom URL.

The following code, thanks to someone over at, works well for redirecting all users after they login.

add_filter( 'login_redirect', function ( $redirect_to, $requested_redirect_to ) {
if ( ! $requested_redirect_to ) {
$redirect_to = wp_get_referer();

return $redirect_to;
}, 10, 2 );

but what I’d like is IF administrator, redirect to custom URL, else, to the referring URL.

I also found this code, but can’t seem to adapt it to the working code above. In fact, even on its own, it doesn’t seem to work.

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

I’ve tried numerous other plugins and snippets, have read everything here, and still, I can’t seem to get it right. If anyone might be able to lend a hand or point me to another thread I may have missed, that would be great.

Thank you!