I wish to create a custom capability for accessing the interface of my plugin.
- Should the plugin manage adding this capability to all the administrator accounts on activation?
- If so: Does WordPress manage adding the capability to all administrators of sub blogs and super administrators in multisite installations, or does that function need to be handled by the plugin?
Tested with WordPress 6.0, and it works:
In the array, you have just some examples of capabilities. And you can add your custom capability without any problem. The custom capability will be stored together with the other capabilities.
With this method, you will not be able to say what you can do with “your_custom_capability”, but most of the time like in the case of this question, you need nothing else than checking if the current user can “your_custom_capability”.
If you want to show your plugin setting pages only to the users who have the capability “your_custom_capability”, you can do it without problems.
Use the inbuilt capabilities when you create the role to decide what are the other things that the user with the role “your_custom_role_slug” should be able to see and do.
This will return true if the user has the role “your_custom_role_slug”:
And this will show the settings page only if the user has the capability “your_custom_capability”:
Then on plugin deletion, I would remove the user role with:
For a plugin I’m currently working on, I wanted to grant/restrict access to the plugin settings (i.e., the according admin menu pages) on a per role base.
Therefore, I had to add a new plugin-specific
capability
to theuser roles
.Unfortunately, kaiser’s answer seems to be not working anymore, so I spent some time trying to figure out how to allow for the above mentioned functionality.
The Schedule
Before I share my code with you, here is what it’s all about, in plain text:
THE_NEW_CAP
to roles having a certain built-in capabilityBUILT_IN_CAP
(in my case:edit_pages
).The Code
And here is the above list converted into code:
» Setting It Up
» Using It
» Cleaning It Up
Note: Please do not use upper case capabilities. This is just for readability.
Remove what you add
First, please make sure that everything you add on activation also gets removed on uninstall. I got a short tutorial including example code for you.
Test with a small plugin:
I really don’t know much about MU, but as far as I can tell, the roles object is global across all blogs. Just try this little plugin and see what you can get:
Adding Capabilities
Note: You can add the capability to the role without granting access to it – just set the second argument
$grant = false;
. This allows whitelisting single users with simply adding the cap including the last argument as true.This works for me: