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.

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

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

Recent Posts
Showing 6 comments
  • Anthony Brown

    Updated function with minor bugfix.

  • Anonymous

    Your function didn't seem to work for me. I had to replace count( $r ) on line 22 with $wpdb->num_rows. Otherwise, thanks for the useful function!

  • Nicholas S Stratton

    it is escaping me but, how do I save the selection of the dropdown menu to the database, I added another column to sales log page of wp e-commerce for this dropdown menu of staff role users so I can assign a staff member to specific sales. so now I need to save to the db the staff member I select from this dropdown.

  • Nicholas S Stratton

    Anthony Brown – wondering if you seen this message yet?

  • Julian Iolrickx

    This function gives an error as:
    Warning: implode() [function.implode]: Invalid arguments passed .

    To make it work, $role_data_ids must be declarated as an array before foreach loop.

    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();
    $role_data_ids = array();
    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">Selecteaza partener</option>';
    $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;

  • El Silva

    da vezi când postezi de pe facebook. apare la tăți pretenii să vază

Leave a Comment