The add_role() WordPress PHP function adds a new role to your WordPress site if it does not already exist.
Usage
Here’s a simple example of using the add_role() function:
add_role('example_role', 'Example Role', array('read' => true, 'edit_posts' => true));
In this example, we’re creating a role named ‘example_role’, with the display name ‘Example Role’. This role has two capabilities: ‘read’ and ‘edit_posts’.
Parameters
- $role (string) (Required): The unique name of the role.
- $display_name (string) (Required): The human-readable name of the role.
- $capabilities (array) (Optional): An associative array of capabilities for this role, with the capability name as the key (e.g., ‘edit_posts’ => true, ‘delete_posts’ => false). Default is an empty array.
More information
See WordPress Developer Resources: add_role()
The add_role() function is not deprecated, and it’s best practice to use this function within an activation hook or a conditional block, as there’s no need for this to execute every time the page loads. It’s important to note that if the role already exists, the function will simply do nothing.
Examples
Creating a Simple Role
This example creates a basic ‘editor_extended’ role that has the capabilities to read, edit posts, and publish posts.
add_role( 'editor_extended', 'Extended Editor', array( 'read' => true, 'edit_posts' => true, 'publish_posts' => true, ) );
Adding Role on Plugin Activation
This example demonstrates how to add a role when a plugin is activated. The function ‘add_roles_on_plugin_activation’ is hooked to the plugin activation, and it adds a ‘custom_role’.
function add_roles_on_plugin_activation() { add_role('custom_role', 'Custom Subscriber', array('read' => true, 'level_0' => true)); } register_activation_hook(__FILE__, 'add_roles_on_plugin_activation');
Cloning an Existing Role
In this example, we’re creating a new role ‘manager’ that clones all capabilities from the ‘editor’ role.
add_role('manager', 'Manager', get_role('editor')->capabilities);
Creating a Role with Custom Capabilities
This example creates a ‘guest_author’ role that has the capabilities to read and edit posts but cannot delete posts.
$result = add_role( 'guest_author', __('Guest Author', 'testdomain'), array( 'read' => true, 'edit_posts' => true, 'delete_posts' => false, ) );
Updating a Role
This example demonstrates updating an existing role’s capabilities. First, the ‘editor’ role is removed, and then added back with additional capabilities.
remove_role('editor'); add_role( 'editor', 'Editor', array( 'read' => true, 'edit_posts' => true, 'delete_posts' => true, 'publish_posts' => true, 'moderate_comments' => true, ) );
Remember, this is for development only and once your capabilities are finalized, there’s no need to keep the remove_role() code.