WP_Roles::add_rolepublicWP 2.0.0

Adds a role name with capabilities to the list.

Updates the list of roles, if the role doesn't already exist.

The list of capabilities can be passed either as a numerically indexed array of capability names, or an associative array of boolean values keyed by the capability name. To explicitly deny the role a capability, set the value for that capability to false.

Examples:

// Add a role that can edit posts.
wp_roles()->add_role( 'custom_role', 'Custom Role', array(
	'read',
	'edit_posts',
) );

Or, using an associative array:

// Add a role that can edit posts but explicitly cannot not delete them.
wp_roles()->add_role( 'custom_role', 'Custom Role', array(
	'read' => true,
	'edit_posts' => true,
	'delete_posts' => false,
) );

Method of the class: WP_Roles{}

No Hooks.

Returns

WP_Role|null. WP_Role object, if the role is added.

Usage

global $wp_roles;
$wp_roles->add_role( $role, $display_name, $capabilities );
$role(string) (required)
Role name.
$display_name(string) (required)
Role display name.
$capabilities(array<string,bool>|array<int,string>)
Capabilities to be added to the role.
Default: empty array

Changelog

Since 2.0.0 Introduced.
Since 6.9.0 Support was added for a numerically indexed array of strings for the capabilities array.

WP_Roles::add_role() code WP 7.0

public function add_role( $role, $display_name, $capabilities = array() ) {
	if ( empty( $role ) || isset( $this->roles[ $role ] ) ) {
		return;
	}

	if ( wp_is_numeric_array( $capabilities ) ) {
		$capabilities = array_fill_keys( $capabilities, true );
	}

	$this->roles[ $role ] = array(
		'name'         => $display_name,
		'capabilities' => $capabilities,
	);
	if ( $this->use_db ) {
		update_option( $this->role_key, $this->roles, true );
	}
	$this->role_objects[ $role ] = new WP_Role( $role, $capabilities );
	$this->role_names[ $role ]   = $display_name;
	return $this->role_objects[ $role ];
}