add_role( string $role, string $display_name, array $capabilities = array() )
Add role, if it does not exist.
Description
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
(WP_Role|null) WP_Role object if role is added, null if already exists.
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 ); }
Changelog
Version | Description |
---|---|
2.0.0 | Introduced. |
Be sure to use this function (and similar role functions) only in an activation hook or within a conditional block. There is no need for this to execute every time the page loads, and it will keep updating the database every time it’s called.
For example, this will store an option to track the version of the custom roles and will only update the database once:
Create a new role when a plugin is activated
See
register_activation_hook
.Example
Create a new “Guest Author” role.
Expand full source codeCollapse full source code
Usage
Note: When to call
Make sure the global
$wp_roles
is 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-plugins
loads 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 returnnull
is 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.