The add_user_role WordPress PHP action fires immediately after the user has been given a new role.
Usage
add_action('add_user_role', 'your_custom_function', 10, 2); function your_custom_function($user_id, $role) { // your custom code here }
Parameters
$user_id
(int) – The user ID.$role
(string) – The new role.
More information
See WordPress Developer Resources: add_user_role
Examples
Send an email when a user is given a new role
Notify the user via email when their role has been changed.
add_action('add_user_role', 'send_email_on_role_change', 10, 2); function send_email_on_role_change($user_id, $role) { $user = get_userdata($user_id); $email_subject = 'Your role has been changed'; $email_message = 'Hi ' . $user->display_name . ', your role has been changed to ' . $role . '.'; wp_mail($user->user_email, $email_subject, $email_message); }
Log role changes
Log the role changes to a custom log file.
add_action('add_user_role', 'log_role_changes', 10, 2); function log_role_changes($user_id, $role) { $user = get_userdata($user_id); $log_message = 'User ' . $user->display_name . ' (' . $user_id . ') has been given the ' . $role . ' role.' . PHP_EOL; error_log($log_message, 3, '/path/to/your/custom_log_file.log'); }
Add custom capabilities based on new role
Add custom capabilities to the user based on their new role.
add_action('add_user_role', 'add_custom_capabilities', 10, 2); function add_custom_capabilities($user_id, $role) { $user = new WP_User($user_id); if ($role == 'editor') { $user->add_cap('edit_others_posts'); } }
Remove capabilities when a user is given a new role
Remove certain capabilities when a user is given a new role.
add_action('add_user_role', 'remove_custom_capabilities', 10, 2); function remove_custom_capabilities($user_id, $role) { $user = new WP_User($user_id); if ($role == 'subscriber') { $user->remove_cap('publish_posts'); } }
Trigger custom events based on new role
Trigger a custom event when a user is given a specific role.
add_action('add_user_role', 'trigger_custom_event', 10, 2); function trigger_custom_event($user_id, $role) { if ($role == 'administrator') { // Trigger your custom event for administrators } }