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()


Top ↑

Return Return

(WP_Role|null) WP_Role object if role is added, null if already exists.


Top ↑

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 );
}

Top ↑

Changelog Changelog

Changelog
Version Description
2.0.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 2 content
    Contributed by Codex

    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.';
    }
  2. Skip to note 3 content
    Contributed by Codex

    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' );
  3. Skip to note 4 content
    Contributed by Codex

    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 your add_role() call if you’re doing this in the context of an mu-plugin.

  4. Skip to note 5 content
    Contributed by Codex

    Note: Delete existing role
    You can not change the capabilities of an existing role using add_role(). This function will stop executing and return null is the specified role name already exists.

    You can change a user role’s capabilities (or display name) by using remove_role(), then add_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.

You must log in before being able to contribute a note or feedback.