WP_User::add_role() WordPress Method

The WP_User::add_role() method allows you to add a role to a user. This is useful if you want to add a new role to a user, or if you want to change the user's role.

WP_User::add_role( string $role ) #

Adds role to user.


Description

Updates the user’s meta data option with capabilities and roles.


Top ↑

Parameters

$role

(string)(Required)Role name.


Top ↑

Source

File: wp-includes/class-wp-user.php

	public function add_role( $role ) {
		if ( empty( $role ) ) {
			return;
		}

		if ( in_array( $role, $this->roles, true ) ) {
			return;
		}

		$this->caps[ $role ] = true;
		update_user_meta( $this->ID, $this->cap_key, $this->caps );
		$this->get_role_caps();
		$this->update_user_level_from_caps();

		/**
		 * Fires immediately after the user has been given a new role.
		 *
		 * @since 4.3.0
		 *
		 * @param int    $user_id The user ID.
		 * @param string $role    The new role.
		 */
		do_action( 'add_user_role', $this->ID, $role );
	}


Top ↑

Changelog

Changelog
VersionDescription
2.0.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.