user_switching_redirect_to
Filters the redirect location after a user switches to another account or switches off. Filters the redirect location after a user switches to or from another account.
add_filter( 'user_switching_redirect_to', $callback, 10, 4 );
Description
Allow developers to modify the redirect URL after a user switch. This filter is applied after a user logs in as another user or logs back into their original account, enabling custom redirection logic based on the switch type, the new user, or the old user.
Usage
add_filter( 'user_switching_redirect_to', 'your_function_name', 10, 4 );
Parameters
-
$redirect_to(string) - The target redirect location, or an empty string if none is specified.
-
$redirect_type(string|null) - The redirect type, see the `user_switching::REDIRECT_*` constants.
-
$new_user(WP_User|null) - The user being switched to, or null if there is none.
-
$old_user(WP_User|null) - The user being switched from, or null if there is none.
Return Value
The filtered value.
Examples
// Redirect administrators to their profile page after switching users.
function my_user_switching_admin_redirect( $redirect_to, $redirect_type, $new_user, $old_user ) {
// Check if we are switching to a user and if the new user is an administrator.
if ( $new_user && in_array( 'administrator', $new_user->roles ) ) {
// If the redirect type is the default 'switch_to', set the redirect to the admin's profile page.
if ( $redirect_type === 'switch_to' ) {
$redirect_to = admin_url( 'profile.php' );
}
}
return $redirect_to;
}
add_filter( 'user_switching_redirect_to', 'my_user_switching_admin_redirect', 10, 4 );
Placement
This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.
Source Code
src/includes/user-switching.php:391
* @since 1.7.0
*
* @param string $redirect_to The target redirect location, or an empty string if none is specified.
* @param string|null $redirect_type The redirect type, see the `user_switching::REDIRECT_*` constants.
* @param WP_User|null $new_user The user being switched to, or null if there is none.
* @param WP_User|null $old_user The user being switched from, or null if there is none.
*/
return apply_filters( 'user_switching_redirect_to', $redirect_to, $redirect_type, $new_user, $old_user );
}
/**
* Displays the 'Switched to {user}' and 'Switch back to {user}' messages in the admin area.
*
* @return void
*/