Best practices for including user switching functionality in another plugin?
Closed this issue · 2 comments
We're discussing adding user switching links to Restrict Content Pro when this plugin is active.
Do you have any suggestions as far as best practices for implementing something like that, and/or are you aware of another plugin that has already done so? I'm sure I could muddle through it, but you're obviously the expert, so I decided to check with you first 😄.
Sure, it's easy enough to do. To check if User Switching is active, just check for the existence of the user_switching
class.
The only method you'll really need to use in your own code is maybe_switch_url()
. This is statically accessed.
user_switching::maybe_switch_url( WP_User $user )
This method takes a WP_User
object. If the current user has the capability to switch to that user then it'll return a URL string which switches them to that user when they visit it, or it'll return boolean false if not. This is a complete wrapper function and you don't need to perform any capability checks yourself.
You can add a redirect_to
query variable to the URL before you output it to the page if you like (make sure to urlencode it). This is the URL the user will be redirected to after they switch. For example:
$link = user_switching::maybe_switch_url( $user );
if ( $link ) {
$link = add_query_arg( 'redirect_to', urlencode( home_url() ), $link );
printf( '<a href="%s">Switch to %s</a>', $link, $user->display_name );
}
You can also take a look at the action_bbpress_button()
method in the plugin. This outputs a link for switching to a bbPress user, so it's quite close to what you want to do.
@johnbillion thanks for this! Hopefully will get it into RCP soon in https://github.com/pippinsplugins/Restrict-Content-Pro/pull/138
👍