The Members WordPress plugin by Justin Tadlock is an incredible tool for revealing the underbelly of user roles and permissions on your WordPress site. Until I discovered this plugin, my concept of user roles was completely tied up in my code. But with Members, we get an intuitive and comprehensive UI for managing the various roles and capabilities that a site’s users may have.
I often wonder why so many plugins contain hooks and filters that they don’t document, and I recently found a good example with the Members plugin.
My task was to filter out certain roles from the list shown below, depending on the logged-in user and what role(s) they have.
In particular, the Administrator role is the top level of access. So for any users that are not Administrators but who still have the ability to edit roles, we want to make sure that they can’t see or edit the Administrator role using the Members UI.
To achieve this, we’d ideally have a hook given to us by the plugin author. It turns out the exact hook we need is offered by the plugin, but it’s more or less hidden within the plugin code several folders deep.
Since Justin uses the
apply_filters function on his array of roles to show on the page, we can hook into his filter named
members_manage_roles_items and perform the conditional logic we need based on the logged-in user.
In the above example, we’re just removing the Administrator role for non-Administrators, but of course this is just one example of what you can do.
Another thing to keep in mind is that we have not removed the actual ability for the logged-in user to edit the Administrator role. We have just hidden the role from them on this one particular screen.
To truly remove the ability for certain users to edit certain roles, we can use the WordPress core
editable_roles filter. Among other things, this makes it so that lower-level users cannot create Administrators on the site.
The combination of the
editable_roles hook and the
members_manage_roles_items hook works well since the former can remove permissions to edit certain roles, and the latter can remove the ability to see certain roles in the Members table.