WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/add role

Description

Adds a new role to WordPress.

NB: This setting is saved to the database (in table wp_options, field wp_user_roles (`wp_` should be changed to match your database prefix defined in wp-config.php)), so it might be better to run this on theme/plugin activation

Usage

 <?php add_role$role$display_name$capabilities ); ?> 

Parameters

$role
(string) (required) Role name
Default: None
$display_name
(string) (required) Display name for role
Default: None
$capabilities
(array) (optional) Array of capabilities (see Roles and Capabilities for list of available capabilities)
Default: array()

Returns

(mixed) 
Returns a WP_Role object on success, null if that role already exists.

Example

Create a new "Basic Contributor" role.

$result = add_role(
    'basic_contributor',
    __( 'Basic Contributor' ),
    array(
        'read'         => true,  // true allows this capability
        'edit_posts'   => true,
        'delete_posts' => false, // Use false to explicitly deny
    )
);
if ( null !== $result ) {
    echo 'Yay! New role created!';
}
else {
    echo 'Oh... the basic_contributor role already exists.';
}

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, 'edit_posts' => true ) );
   }
   register_activation_hook( __FILE__, 'add_roles_on_plugin_activation' );

Notes

When to call

Make sure that the global $wp_roles is available before attempting to add or modify a role. The best practice of course is to use your plugin- or theme-activation hook to make changes to roles (since you only want to do it once!).

mu-plugins will load too early, so use an action hook (like 'init') to wrap your add_role() call if you're doing this in the context of an mu-plugin.

Delete existing role

If you are defining a custom role, and adding capabilities to the role using add_role(), be aware that modifying the capabilities array and re-executing add_role() will not necessarily update the role with the new capabilities list. The add_role() function short-circuits if the role already exists in the database.

The workaround in this case is to precede your add_role() call with a remove_role() call that targets the role you are adding.

This is for development only. Once you have nailed down your list of capabilities, there's no need to keep the remove_role() code, though there is, in fact, no harm in doing so.

Changelog

Source Code

add_role() is located in wp-includes/capabilities.php.

Related

Roles and Capabilities:
See also index of Function Reference and index of Template Tags.