wp_ensure_editable_role()WP 6.8.0

Checks whether the current user can assign the specified role to another user.

The function receives the role name and compares it against the list of roles available to the current user for editing. If the role cannot be assigned, the script execution is immediately stopped via wp_die() and an error message is displayed.

The function does not check whether the role exists directly. It checks the role specifically among the roles that the current user is allowed to edit. Therefore, the role may exist in WordPress, but still be unavailable for assignment.

The function is located in wp-admin/includes/ms.php, so it is usually used in the admin area.

No Hooks.

Returns

null.

  • void — returns nothing if the role can be assigned.
  • void — if the role cannot be assigned, terminates execution via wp_die().

Usage

wp_ensure_editable_role( $role );
$role(string) (required)

The name of the role that the user is trying to assign.

For example: subscriber, editor, administrator.

Examples

0

#1 Role check before assigning a user

Before updating the role, you can check whether the current user is allowed to assign such a role.

$role = 'editor';

wp_ensure_editable_role( $role );

$user_id = 25;
$user    = new WP_User( $user_id );

$user->set_role( $role );

If the current user cannot assign the editor role, execution will be stopped.

0

#2 Role Check from Form Data

The example shows how to verify the role passed from the form in the admin area.

if ( isset( $_POST['role'] ) ) {
	$role = sanitize_key( $_POST['role'] );

	wp_ensure_editable_role( $role );

	$user_id = 25;
	$user    = new WP_User( $user_id );

	$user->set_role( $role );
}

Changelog

Since 6.8.0 Introduced.

wp_ensure_editable_role() code WP 7.0

function wp_ensure_editable_role( $role ) {
	$roles = get_editable_roles();
	if ( ! isset( $roles[ $role ] ) ) {
		wp_die( __( 'Sorry, you are not allowed to give users that role.' ), 403 );
	}
}