WP_REST_Users_Controller::update_item()publicWP 4.7.0

Updates a single user.

Method of the class: WP_REST_Users_Controller{}

Return

WP_REST_Response|WP_Error. Response object on success, or WP_Error object on failure.

Usage

$WP_REST_Users_Controller = new WP_REST_Users_Controller();
$WP_REST_Users_Controller->update_item( $request );
$request(WP_REST_Request) (required)
Full details about the request.

Changelog

Since 4.7.0 Introduced.

WP_REST_Users_Controller::update_item() code WP 6.6.2

public function update_item( $request ) {
	$user = $this->get_user( $request['id'] );
	if ( is_wp_error( $user ) ) {
		return $user;
	}

	$id = $user->ID;

	$owner_id = false;
	if ( is_string( $request['email'] ) ) {
		$owner_id = email_exists( $request['email'] );
	}

	if ( $owner_id && $owner_id !== $id ) {
		return new WP_Error(
			'rest_user_invalid_email',
			__( 'Invalid email address.' ),
			array( 'status' => 400 )
		);
	}

	if ( ! empty( $request['username'] ) && $request['username'] !== $user->user_login ) {
		return new WP_Error(
			'rest_user_invalid_argument',
			__( 'Username is not editable.' ),
			array( 'status' => 400 )
		);
	}

	if ( ! empty( $request['slug'] ) && $request['slug'] !== $user->user_nicename && get_user_by( 'slug', $request['slug'] ) ) {
		return new WP_Error(
			'rest_user_invalid_slug',
			__( 'Invalid slug.' ),
			array( 'status' => 400 )
		);
	}

	if ( ! empty( $request['roles'] ) ) {
		$check_permission = $this->check_role_update( $id, $request['roles'] );

		if ( is_wp_error( $check_permission ) ) {
			return $check_permission;
		}
	}

	$user = $this->prepare_item_for_database( $request );

	// Ensure we're operating on the same user we already checked.
	$user->ID = $id;

	$user_id = wp_update_user( wp_slash( (array) $user ) );

	if ( is_wp_error( $user_id ) ) {
		return $user_id;
	}

	$user = get_user_by( 'id', $user_id );

	/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php */
	do_action( 'rest_insert_user', $user, $request, false );

	if ( ! empty( $request['roles'] ) ) {
		array_map( array( $user, 'add_role' ), $request['roles'] );
	}

	$schema = $this->get_item_schema();

	if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) {
		$meta_update = $this->meta->update_value( $request['meta'], $id );

		if ( is_wp_error( $meta_update ) ) {
			return $meta_update;
		}
	}

	$user          = get_user_by( 'id', $user_id );
	$fields_update = $this->update_additional_fields_for_object( $user, $request );

	if ( is_wp_error( $fields_update ) ) {
		return $fields_update;
	}

	$request->set_param( 'context', 'edit' );

	/** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php */
	do_action( 'rest_after_insert_user', $user, $request, false );

	$response = $this->prepare_item_for_response( $user, $request );
	$response = rest_ensure_response( $response );

	return $response;
}