How do I list in the backend all users that were assigned to a custom role?

From my previous question How to create and retrieve data from a special registration form? I would like to know how do I list in the backend all users that were assigned to a custom role? Is it possible to put them in a separate admin page?

1 Answer
1

User queries

There is a WP_User_Query, analogous to WP_Query for posts:

$wp_user_search = new WP_User_Query( array( 'role' => 'editor' ) );
$editors = $wp_user_search->get_results();

Usually this returns an array of row objects from the user table:

echo '<ul>';
foreach ($editors as $editor):
  echo '<li>'.$edtior->display_name.'</li>';
endforeach;
echo '</ul>';

However you can specify it to instead return an array of WP_User objects by including 'fields'=>'all_with_meta' in the array passed to WP_User_Query.

Register Admin Page

To register admin menus you need to hook a function onto 'admin_menu' which calls add_submenu_page (or add_menu_page if you want a top-level page). See the Codex.

In this case adding the page under the ‘users’ tab seems appropriate, and the hook for that is ‘users.php’.

add_action('admin_menu', 'register_my_custom_submenu_page');
function register_my_custom_submenu_page() {
    //Register submenu page underneath users tab.
    add_submenu_page('users.php','My Editors', 'My Editor','manage_options','my-editors', 'my_editor_page_callback',10);
}
//This is the callback function specified above
//This outputs the content of your page.
function my_editor_page_callback(){
    ?>
        <div class="wrap">
            <div class="icon32" id="icon-users"><br></div>
            <h2>My Editors</h2>
    <?php
}
?>

If you wanted to have a table on this page, listing only users of a specific role, you may want to consider looking at the WP_List_Table plug-in. It’s not really a plug-in but an example of how to use the WP_List_Table class. (Using this you could include extra columns for user meta data etc.). (Note, however, the default user table does already allow you to filter by user).

Leave a Comment