Skip to content

Instantly share code, notes, and snippets.

@wpmark
Last active Jul 26, 2017
Embed
What would you like to do?
Plugin to add a dropdown list of users in the WordPress admin bar with a link to switch to that user (requires the User Switching plugin by http://profiles.wordpress.org/johnbillion/).
<?php
/**
Plugin Name: User Switching in Admin Bar
Plugin URI: http://markwilkinson.me
Description: Build upon the User Switching plugin (http://wordpress.org/extend/plugins/user-switching/) by John Blackbourn and adds a dropdown list of users in the WordPress admin bar with a link to switch to that user.
Author: Mark Wilkinson
Author URI: http://markwilkinson.me
Version: 1.0
*/
/* alter the wordpress admin bar */
function pxjn_user_switching_adminbar() {
/* include plugin file to make this work on the front end */
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
/* check whether the user switching plugin is active */
if( is_plugin_active( 'user-switching/user-switching.php' ) ) {
global $user_switching;
/* load the global admin bar variable */
global $wp_admin_bar;
/* check whether the current user is super admin */
if( is_super_admin() ) {
/* add admin bar menu for switching to a user */
$wp_admin_bar->add_menu( array(
'id' => 'pxjn_switch_to_user',
'title' => 'Switch to User',
'href' => '#',
) );
/* set some arguments for our user query */
$pxjn_user_query_args = array(
'role' => '',
'orderby' => 'display_name'
);
/* begin build of switch user url */
$pxjn_switch_user_url_base = wp_login_url();
/* create a new user query */
$pxjn_user_query = new WP_User_Query( $pxjn_user_query_args );
/* store results from user query */
$pxjn_users = $pxjn_user_query->get_results();
/* check we have users */
if( !empty( $pxjn_users ) ) {
/* loop through each user */
foreach( $pxjn_users as $pxjn_user ) {
/* get all of this users data */
$pxjn_user_info = get_userdata( $pxjn_user->ID );
/* build query args for this user */
$pxjn_switch_user_query_args = array(
'action' => 'switch_to_user',
'user_id' => $pxjn_user->ID
);
/* build menu url */
$pxjn_full_menu_url = $user_switching->switch_to_url( $pxjn_user->ID );
/* build menu id for each user */
$pxjn_menu_id = $pxjn_user_info->first_name . $pxjn_user_info->last_name;
/* add admin bar menu to create a new appraisal */
$wp_admin_bar->add_menu( array(
'id' => $pxjn_menu_id,
'parent' => 'pxjn_switch_to_user',
'title' => $pxjn_user_info->display_name,
'href' => $pxjn_full_menu_url,
) );
} //
} // check we have users
} // check we are super admin
} // check user switching plugin is active
}
add_action('wp_before_admin_bar_render', 'pxjn_user_switching_adminbar', 0);
@johnbillion
Copy link

Mark, I've just updated this Gist to support some changes I made in User Switching 0.8.

https://gist.github.com/johnbillion/6087274/revisions

John

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment