WP_Roles::add_role( string $role, string $display_name, array|array $capabilities = array() ): WP_Role|void

Adds a role name with capabilities to the list.

Description

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

Parameters

$rolestringrequired
Role name.
$display_namestringrequired
Role display name.
$capabilities<span class="array”>array|<span class="array”>arrayoptional
Capabilities to be added to the role.

Default:array()

Return

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

Source

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

Changelog

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

User Contributed Notes

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