WordPress get user dropdown by role

We needed a function to get a user selectbox by the user role. Instead of using the native wordpress function wp_dropdown_users() to get a list of all users we decided to create our own.

This function allows you to easily create a dropdown based on the user role.

function getUsersByRole($role,$name,$selected = '',$extra = '') {
global $wpdb;

	  $wp_user_search = new WP_User_Query(array("role"=> $role));
   	  $role_data = $wp_user_search->get_results();
		 foreach($role_data  as $item){
			 $role_data_ids[] = $item->ID;
		 }

	  $ids = implode(',', $role_data_ids);
	  $r = $wpdb->get_results("SELECT *   from ".$wpdb->prefix . "users where id IN(".$ids .")", ARRAY_A);

	  $content .='<select name="'.$name.'" id="'.$name.'" '.$extra.'>';

	  if($selected == ''){
			$content .='<option value="" selected="selected">Choose a user</option>';
		}else{
				$r_user = $wpdb->get_results("SELECT *   from ".$wpdb->prefix . "users where ID = ".$selected."", ARRAY_A);
				$content .='<option value="'.$selected.'" selected="selected">'.stripslashes($r_user[0]['display_name']).'</option>';
		}

	  for($i=0; $i<count($r); $i++){		  	
	  $content .='<option value="'.$r[$i]['ID'].'">'.stripslashes($r[$i]['display_name']).'</option>';
	  }
	  $content .='</select>';

	  return $content;
}

Now to use this function in your plugin do the following:

// the first field is the user role
// the second field is the name and id attributes for the selectbox
//the third field is optional and will allow you to set a selected state
// the fourth field optional is any special attributes you want to add into the select for instance an on change

echo getUsersByRole('subscriber','user_id', $r[0]['user_id'],'onchange="dosomething()"');

// or just use which will not set a default selected user or any extra attributes
echo getUsersByRole('subscriber','user_id');

If you have any questions please ask, this also works with the role editor plugin. (great for custom roles!)

Recent Posts

Leave a Comment