Question

I am using get_users() to return a list of users with specified roles. The purpose of this is to generate a dropdown on the front end to mention other users in comments, very similar to the functionality of https://wordpress.org/plugins/comment-mention/.

The problem is that if the current user is in a lower role, such as an author, get_users() does not return higher roles, such as an administrator. In other words, I need a lower user to be able to return users of higher roles as well.

I realised that get_users() prevents return higher role users from here: get_users / WP_User_Query returns empty when logged out

But I wondered if there was a way around this. This is how I am getting the list of users at the moment

<?php
// Set arguments.
$args = array(
    'fields' => array('user_login'),
    'role__in' => array('administrator','editor','author'),
);

// Get usernames.
$results = get_users( $args );
?>

Just a note here, the desired final result is to return an array of all usernames.

Was it helpful?

Solution 2

The cause of the problem I was having is related to the "Toolset Access" plugin from the toolset.com group of plugins.

By default, this plug has an option that does not allow users to edit other users with a higher role than themselves. This impacts a wide range of WordPress functions such as get_users() and wp_dropdown_users().

The functionality can be disabled from plugin settings, see screenshot below: enter image description here

Be aware that you should consider your own use case, as this would allow users with lower capabilities, who can edit users, to edit those above them. In my case, I don't give my lower users this type of access anyway.

OTHER TIPS

You wrote you need to generate a dropdown list with users. As I thought right - not tied to roles.

wp_dropdown_users() maybe helpful. It will generate a dropdown list for you. Just checked on my wp install, it's still returning me a list of all users, doesn't matter if I logged in as administrator or subscriber.

wp_dropdown_users() has a lot of attributes, which may be useful in your case - include, exclude users, show users by roles, show default value if no user was selected and so on.

Pay attention, that this function echoes html select list by default, attribute 'echo' should be set to false if you want to get html code in a variable.

wp_dropdown_users code reference

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top