add_role( string $role, string $display_name, array $capabilities = array() )
Add role, if it does not exist.
Description Description
Parameters Parameters
- $role
-
(string) (Required) Role name.
- $display_name
-
(string) (Required) Display name for role.
- $capabilities
-
(array) (Optional) List of capabilities, e.g. array( 'edit_posts' => true, 'delete_posts' => false );
Default value: array()
Return Return
(WP_Role|null) WP_Role object if role is added, null if already exists.
Source Source
File: wp-includes/capabilities.php
function add_role( $role, $display_name, $capabilities = array() ) {
if ( empty( $role ) ) {
return;
}
return wp_roles()->add_role( $role, $display_name, $capabilities );
}
Expand full source code Collapse full source code View on Trac
Changelog Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |
User Contributed Notes User Contributed Notes
You must log in before being able to contribute a note or feedback.
Usage
Example
Create a new “Guest Author” role.
$result = add_role( 'guest_author', __( 'Guest Author', 'testdomain' ), array( 'read' => true, // true allows this capability 'edit_posts' => true, 'delete_posts' => false, // Use false to explicitly deny ) ); if ( null !== $result ) { echo "Success: {$result->name} user role created."; } else { echo 'Failure: user role already exists.'; }Expand full source codeCollapse full source code
Create a new role when a plugin is activated
See
register_activation_hook.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' );Note: When to call
Make sure the global
$wp_rolesis available before attempting to add or modify a role. The best practice is to use a plugin (or theme) activation hook to make changes to roles (since you only want to do it once!).mu-pluginsloads too early, so use an action hook (like'init') to wrap youradd_role()call if you’re doing this in the context of an mu-plugin.Note: Delete existing role
You can not change the capabilities of an existing role using
add_role(). This function will stop executing and returnnullis the specified role name already exists.You can change a user role’s capabilities (or display name) by using
remove_role(), thenadd_role().This is for development only. Once you have nailed down your list of capabilities, there’s no need to keep the remove_role() code.