The remove_user_role WordPress PHP action fires immediately after a role has been removed from a user.
Usage
add_action('remove_user_role', 'my_custom_function', 10, 2); function my_custom_function($user_id, $role) { // Your custom code here }
Parameters
$user_id
(int) – The user ID.$role
(string) – The removed role.
More information
See WordPress Developer Resources: remove_user_role
Examples
Log Role Removal
Log when a role is removed from a user.
function log_role_removal($user_id, $role) { $user = get_userdata($user_id); $message = "Role '{$role}' has been removed from user '{$user->user_login}' (ID: {$user_id})"; error_log($message); } add_action('remove_user_role', 'log_role_removal', 10, 2);
Send Email Notification
Send an email notification when a user loses an ‘editor’ role.
function notify_user_role_removal($user_id, $role) { if ($role === 'editor') { $user = get_userdata($user_id); $email_subject = 'Role Removed'; $email_message = "Hello {$user->display_name},\n\nYour Editor role has been removed from your account."; wp_mail($user->user_email, $email_subject, $email_message); } } add_action('remove_user_role', 'notify_user_role_removal', 10, 2);
Revoke Capabilities
Revoke additional capabilities when a custom role is removed.
function revoke_custom_role_capabilities($user_id, $role) { if ($role === 'custom_role') { $user = new WP_User($user_id); $user->remove_cap('custom_capability'); } } add_action('remove_user_role', 'revoke_custom_role_capabilities', 10, 2);
Count Role Removals
Count how many times a role has been removed from users.
function count_role_removals($user_id, $role) { $count_key = "removed_{$role}_count"; $count = get_option($count_key, 0); update_option($count_key, ++$count); } add_action('remove_user_role', 'count_role_removals', 10, 2);
Trigger Custom Action
Trigger a custom action when a specific role is removed.
function trigger_custom_action_on_role_removal($user_id, $role) { if ($role === 'specific_role') { do_action('custom_action', $user_id); } } add_action('remove_user_role', 'trigger_custom_action_on_role_removal', 10, 2);