2

I need to fetch the list of all users who are Authors (with Author capabilities)

get_users allows to fetch users with roles, but if users are filter with author role, it skips users with role admin and editor (but they can also create posts).

So I need some other way to fetch all users having capability of Author Role (they can be from Administator, Editor or any other custom roles with Authors capability)

To Be more precise - Need all users with "publish_posts" capability.

3

Here's a way to collect roles with the publish_posts capability:

$roles__in = [];
foreach( wp_roles()->roles as $role_slug => $role )
{
    if( ! empty( $role['capabilities']['publish_posts'] ) )
        $roles__in[] = $role_slug;
}

and then we can query users with these roles:

if( $roles__in )
    $users = get_users( [ 'roles__in' => $roles__in, 'fields' => 'ids' ] );

where we might need pagination for large amount of users.

One can also loop over few users and check with:

user_can( $user, 'publish_posts' )

See docs here.

  • 1
    Capabilities can be assigned to and removed from single users; capabilities not only belongs to roles but also to users. Not sure if it is possible to get all users with a specific capability in a easy way. – cybmeta Oct 2 '17 at 9:23
  • yes that's a good point @cybmeta - I also added another per user check but that might be less scalable – birgire Oct 2 '17 at 9:26
2

Basically, there are 3 roles who have a right to publish post - "Administrator", "Editor" & "Author", unless you are adding any custom roles.

So you can do is specify an array of these 3 in your get_users function. Something like this:

get_users( array(
        'role__in'     => array('administrator', 'editor', 'author'),
    ) );

This will give you the user details with these roles in array which you can use as convenience.

Hope this helps.

Thanks

0

Use get_role() for getting capabilities from any role of the user in your code.

  • I need all users with "publish_posts" capability. how to do it? – Anand Oct 2 '17 at 7:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.