Instantly share code, notes, and snippets.

Embed
What would you like to do?
Conditional Custom Login Redirects in WordPress
function wip_login_redirect( $url, $request, $user ){
// Define referrer
$slug = $_SERVER["REQUEST_URI"];
// Define slugs of any referrers you want here
// For example, if they page you want to target
// is www.testsite.com/hello-world
// you'll want this:
// $islogin = strpos($slug, 'hello-world');
$islogin = strpos($slug, 'log-in');
// Need to tap into the WP_User Object
// And make sure they are a user
if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
// If user is an Admin and they're
// logging in at our custom login page
// redirect them to wp-admin
if(($user->has_cap('edit_users')) && ($islogin==true)) {
$url = admin_url('index.php');
// But, if they are logging in at
// our custom login page and ARE NOT
// an Admin, redirect them to the homepage
} elseif ((!$user->has_cap('edit_users')) && ($islogin==true)) {
$url = home_url();
// If neither of those is true,
// They the user is logging in via a front-end form
// So it's best to just redirect them to that page
} else {
$url = $slug;
}
}
return $url;
}
add_filter('login_redirect', 'wip_login_redirect', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment