Users: Bring some consistency to user role hooks.

This standardizes the actions that one needs to hook to for tracking user role changes:

* `add_user_role` is only fired when the user has actually gained a new role.
* `remove_user_role` is only fired when the role was actually removed.

Both actions are now fired in `WP_User::set_role()` as appropriate.

Props dd32, SergeyBiryukov.
Fixes #54164.
Built from https://develop.svn.wordpress.org/trunk@52823


git-svn-id: http://core.svn.wordpress.org/trunk@52412 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Sergey Biryukov 2022-03-06 16:11:04 +00:00
parent 4ae0744585
commit 78911c2f60
2 changed files with 23 additions and 2 deletions

View File

@ -542,6 +542,10 @@ class WP_User {
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();
@ -569,6 +573,7 @@ class WP_User {
if ( ! in_array( $role, $this->roles, true ) ) {
return;
}
unset( $this->caps[ $role ] );
update_user_meta( $this->ID, $this->cap_key, $this->caps );
$this->get_role_caps();
@ -606,16 +611,32 @@ class WP_User {
}
$old_roles = $this->roles;
if ( ! empty( $role ) ) {
$this->caps[ $role ] = true;
$this->roles = array( $role => true );
} else {
$this->roles = false;
$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.
*

View File

@ -16,7 +16,7 @@
*
* @global string $wp_version
*/
$wp_version = '6.0-alpha-52822';
$wp_version = '6.0-alpha-52823';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.