WP_User::set_role( string $role )

Sets the role of the user.

Description

This will remove the previous roles of the user and assign the user the new one. You can set the role to an empty string and it will remove all of the roles from the user.

Parameters

$rolestringrequired
Role name.

Source

public function set_role( $role ) {
	if ( 1 === count( $this->roles ) && current( $this->roles ) === $role ) {
		return;
	}

	foreach ( (array) $this->roles as $oldrole ) {
		unset( $this->caps[ $oldrole ] );
	}

	$old_roles = $this->roles;

	if ( ! empty( $role ) ) {
		$this->caps[ $role ] = true;
		$this->roles         = array( $role => true );
	} else {
		$this->roles = array();
	}

	update_user_meta( $this->ID, $this->cap_key, $this->caps );
	$this->get_role_caps();
	$this->update_user_level_from_caps();

	foreach ( $old_roles as $old_role ) {
		if ( ! $old_role || $old_role === $role ) {
			continue;
		}

		/** This action is documented in wp-includes/class-wp-user.php */
		do_action( 'remove_user_role', $this->ID, $old_role );
	}

	if ( $role && ! in_array( $role, $old_roles, true ) ) {
		/** This action is documented in wp-includes/class-wp-user.php */
		do_action( 'add_user_role', $this->ID, $role );
	}

	/**
	 * Fires after the user's role has changed.
	 *
	 * @since 2.9.0
	 * @since 3.6.0 Added $old_roles to include an array of the user's previous roles.
	 *
	 * @param int      $user_id   The user ID.
	 * @param string   $role      The new role.
	 * @param string[] $old_roles An array of the user's previous roles.
	 */
	do_action( 'set_user_role', $this->ID, $role, $old_roles );
}

Hooks

do_action( ‘add_user_role’, int $user_id, string $role )

Fires immediately after the user has been given a new role.

do_action( ‘remove_user_role’, int $user_id, string $role )

Fires immediately after a role as been removed from a user.

do_action( ‘set_user_role’, int $user_id, string $role, string[] $old_roles )

Fires after the user’s role has changed.

Changelog

VersionDescription
2.0.0Introduced.

User Contributed Notes

  1. Skip to note 5 content

    As @tobi823 said:

    $wpUser->set_role( '' );

    will not work if you set an unregistered role.
    I had this problem setting up a logical deletion by setting a ‘disabled’ user role. Then I couldn’t reenable them, because the disabled role was being kept inside the array.

    Here is my fix for that, by replacing the user role from the submitted role in the user edit field using the user meta:

    $role = array( $_POST['role'] => 1 );
    update_user_meta( $user_id, 'wp_capabilities', $role ); // replaces with the new role

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