How to Add Custom Capabilities to User Roles in WordPress
To add custom capabilities to a user role –
1. Identify the Role:
Determine which user role you want to modify, for example, Administrator, Editor, Author etc.
Add custom capability to a Role:
Use the `add_cap
` method to add capabilities. You can do this in your `functions.php
` file of your theme or in a custom plugin.
function add_custom_capabilities() {
$role = get_role('editor'); //Replace 'editor' with the role you want to modify
if ($role) {
$role->add_cap('custom_capability'); //Replace 'custom_capability' with the capability you want to add
}
}
add_action('admin_init', 'add_custom_capabilities');
Remove Custom Capability from a Role:
Use the `remove_cap
` method to remove capabilities.
function remove_custom_capabilities() {
$role = get_role('editor'); //Replace 'editor' with the role you want to modify
if ($role) {
$role->remove_cap('custom_capability'); //Replace 'custom_capability' with the capability you want to remove
}
}
add_action('admin_init', 'remove_custom_capabilities');
After making changes, test the role to ensure it has the correct capabilities and restrictions.