Yep, you can use the user_switching::maybe_switch_url( $user ) method to get a URL for switching to that user. It returns the URL or boolean false.
if ( $url = user_switching::maybe_switch_url( $user ) ) {
printf( '<a href="%s">Switch to %s</a>', $url, $user->display_name );
}
You can use the same function to get the switch back URL, along with a check for current_user_switched().
if ( $old_user = current_user_switched() && $url = user_switching::maybe_switch_url( $old_user ) ) {
printf( '<a href="%s">Switch back</a>', $url );
}
hey,
thanks for your attention
user_switching::maybe_switch_url( $user ) returns “false” and i’m sure the user has the required capability (that’s admin) so probably because there’s no old user it return false, isn’t it ?
by the way i try user_switching::switch_to_url ( $user ) and it worked. can i use this or it’s not safe ?!
(* Helper function. Returns the nonce-secured URL needed to switch to a given user ID)
and second question : 🙂
when admin switched i want to redirect him to for example “site.com/panel” and when he switched back, get redirected to page that he left (it can be different pages because we have switch link in some pages in admin panel).
so is it possible ?
thanks so much John
user_switching::maybe_switch_url( $user ) is a wrapper for user_switching::switch_to_url ( $user ) which includes the logic to detect whether or not the current user is allowed to switch to the user, etc. I would check to make sure that the value of the $user parameter you’re passing in is correct.
You can control the redirect location by adding a redirect_to parameter to the URL. Example:
if ( $url = user_switching::maybe_switch_url( $user ) ) {
$url = add_query_arg( 'redirect_to', urlencode( home_url( 'panel' ) ), $url );
printf( '<a href="%s">Switch to %s</a>', $url, $user->display_name );
}