User roles and user capabilities are very important aspects when you’re developing a theme or a plugin.
The user role and privileges allow users to perform some action while restricts them to perform certain actions as well.
By default, WordPress stores the user roles and user capabilities in the options table (with user_roles key).
Default WordPress Roles
There are 6 roles by default in WordPress.
- Super Admin
- Administrator
- Editor
- Author
- Contributor
- Subscriber
Since WordPress is flexible, you can remove the default roles or add additional roles as well.
add_role()
To add a new role you need to use add_role() function.
Here’s the syntax:
add_role(
$user_role,
$display_name,
$capabilities
)
Where $user_role and $display_name are required parameters as strings.
In $capabilities parameters, we can pass an array with boolean values and it’s an optional parameter. You can pass a parameter like this:
array(
'edit_posts' => true,
'delete_posts' => false
)
If the roles already exists then the function will simply return null but if it doesn’t exist then the function will return the role object you added.
Example
This example function will add a new user role “Blog Admin Temp” with editor capabilities.
function yc_role() {
add_role(
'guest_editor',
'Guest Editor',
array(
'read' => true,
'edit_posts' => true,
'upload_files' => true,
),
);
}
// Add the yc_role.
add_action( 'init', 'yc_role' );
This is a simple example. You can add more capabilities and make the role a bit more complex.
Here’s the complete list of Roles and Capabilities.
Create a new user role on action
This function will create a new role when a plugin is activated. We can use register_activation_hook to do so.
function add_roles_on_plugin_activation() {
add_role(
'guest_editor',
'Guest Editor',
array(
'read' => true,
'edit_posts' => true,
'upload_files' => true,
),
);
}
register_activation_hook(
__FILE__,
'add_roles_on_plugin_activation'
);
Remove a user role
function user_role_remove() {
remove_role( 'guest_editor' );
}
// Remove the simple_role.
add_action( 'init', 'user_role_remove' );
Once you remove the role, there is no need to call the function again. It won’t do anything anyway.
functions hook role user