So, earlier today I discovered that there is not an easy way to allow users to control user access to various parts of the back end. As far as I can tell, the functions just don’t exist in the core and the two parts WordPress cares about.
The problem is that WordPress controls access to its various components (and to any developer-added components) using capabilities. The capability system is pretty cool, but in order to make it as customizable as possible, they are not tied to specific user roles.
This sounds like a good idea, until you want to create a way for a site’s administrators to give specific user roles the ability to access (or not access) parts of a site or plugin.
Your average user has no interest in checking the user/capability chart every time they want to switch a user’s access. It would be ridiculous to ask them to do so. But just setting up an option for administrators to select user levels is useless to me as a developer, because all the actual functionality resides in setting capabilities matched to things like menus.
So, I need to be able to do a few things in order to make the two ends meet here.
- I need to be able to find out what the user level is based on the capability.
- I need to be able to identify a capability that ‘defines’ a user role, that being one that a user role can do, but that no lower user roles can do.
So, to do all that, I set up three functions.
The first allows you to get just a list of capabilities, with each capability having an array of the user roles that can use it. As an added bonus, it will also allow you to get just a specific capability and its array.
The second allows you to get a role by capability. There are two approaches here, you can get the lowest role or the highest role for any capability. I set the function to be able to do both (plugins and themes can create capabilities that do not propagate up, I think), but by default, it will get the lowest possible user role for the capability parameter.
The third allows you to find that ‘defining’ capability for a user role. By sending the role slug, it will walk through the list until it finds the first capability where the lowest level role is the parameter role. You can then use that capability to set the user level throughout your plugin/theme and then use it to build a set of setting checkboxes or a select where the roles are displayed, but the values are the defining capabilities.
As far as I could tell, WordPress doesn’t have anything set up to do this yet. So here’s the code.