By Raja Usman Mehmood


2016-03-04 05:10:49 8 Comments

How can I get a list of all users that are in WordPress by their role or capabilities?

For example:

  • Display all subscribers list in WordPress.
  • Display all authors list in WordPress.
  • Display all editors list in WordPress.

3 comments

@Wikus 2019-07-09 11:43:09

Expanding on Raja's answer you could also write a helper function that handles this for you:

<?php
# This goes in functions.php
function get_users_by_role($role, $orderby, $order) {
    $args = array(
        'role'    => $role,
        'orderby' => $orderby,
        'order'   => $order
    );

    $users = get_users( $args );

    return $users;
}
?>

Then to get users by a specific role you can simply do:

<?php $users = get_users_by_role('Your role', 'user_nicename', 'ASC'); ?>

@Jevuska 2016-03-04 13:37:57

Here the simple approach to grouping roles.

$wp_roles = wp_roles();
$result   = count_users();

foreach ( $result['avail_roles'] as $role => $count )
{
    if ( 0 == $count )
        continue; //pass role none

    $args = array(
        'role' => $role
    );

    $users = get_users( $args );
    $user  = array();
    for ( $i = 0; $i < $count ; $i++ )
        $user[] = esc_html( $users[ $i ]->display_name ); //show display name

    //output
    echo wp_sprintf( '<h2>%1$s</h2><ul><li>%2$s</li></ul>',
        esc_html( $wp_roles->role_names[ $role ] ),
        implode( '</li><li>', $user )
    );
}

@Raja Usman Mehmood 2016-03-04 05:10:49

There may be some different way to do that, but most proper way to do that is following.

<?php

$args = array(
    'role'    => 'Your desired role goes here.',
    'orderby' => 'user_nicename',
    'order'   => 'ASC'
);
$users = get_users( $args );

echo '<ul>';
foreach ( $users as $user ) {
    echo '<li>' . esc_html( $user->display_name ) . '[' . esc_html( $user->user_email ) . ']</li>';
}
echo '</ul>';

?>

Related Questions

Sponsored Content

1 Answered Questions

[SOLVED] Create role that can edit some user details, but not the role

3 Answered Questions

[SOLVED] How to get all users with Author role capabilities?

3 Answered Questions

[SOLVED] Do custom user roles have any default capabilities?

1 Answered Questions

[SOLVED] How to get all capabilities of an existing user role

1 Answered Questions

[SOLVED] Let users edit their role from the frontend

1 Answered Questions

[SOLVED] How to get a users list by who created them?

1 Answered Questions

[SOLVED] Stop users of author role from editing already pending posts

Sponsored Content