[wp-hackers] Get All Users with Specific capability

Jeremy Clarke jer at simianuprising.com
Wed Feb 16 00:48:51 UTC 2011


In 3.1 you can use get_users('role=subscriber') to avoid using any custom
SQL but like you say that is not usually good enough and capabilities are
fundamentally more useful and important in WP (especially in public plugins
where you can't make any assumptions about roles).

IMHO get_users() should be able to take in a capability as well as roles,
too bad that wasn't included in 3.1. It's certainly a complicated problem,
but it doesn't seem impossible, just potentially irresponsible WRT server
performance (you'd want to cache it if you use it on most pageloads).


On Tue, Feb 15, 2011 at 6:59 PM, Ryan Bilesky <rbilesky at gmail.com> wrote:

> Ok so basically there isn't a better way.  Now I can make this easier by
> caching the resulting array in say a site option, then most the time all I
> have to do is pull a site option.  Then I just need to find the necessary
> hooks pto update the data when it has or may have changed.  So I need to
> find hooks for when role/capabilities are changed and a hook when a user
> changes roles.  Does anyone know of any such hooks, am I missing any otherd
> id need?
>
>
Here's the actions I attach my own user caching system to:

function gv_hook_user_udpate($user_id, $old_user_data = '') {
     gv_update_cached_user($user_id);
}
add_action('profile_update', 'gv_hook_user_udpate', '', 2);
add_action('user_register', 'gv_hook_user_udpate', '', 1);

That seems to cover most scenarios, though there could easily be edge cases
that aren't covered, especially because often cap/role related changes are
made using plugins that probably don't call profile_update after changing a
user. Having this data reload at regular intervals is going to be important.

I'd recommend using the Transients API instead of options, as it will handle
expiration for you: https://codex.wordpress.org/Transients_API

-- 
Jeremy Clarke • jeremyclarke.org
Code and Design • globalvoicesonline.org


More information about the wp-hackers mailing list