How to Send Email Notification When User Role Changes?

If you are managing a WordPress website with multiple users, there may be times when you need to update a user’s role. For example, you may need to promote a user to an SEO editor or demote a user to a subscriber. In these cases, it can be helpful to send an email notification to the user to let them know that their role has been updated.

In this article, we will show you how to send an email to a user when their role is updated in WordPress using the action hook called set_user_role.

What is the set_user_role action hook?

The set_user_role action hook is a WordPress hook that is triggered when a user’s role is updated. It provides three parameters:

  • $user_id :- the ID of the user whose role was updated
  • $new_role :- the new role of the user
  • $old_roles:- An array of the user’s previous roles.

You can use this hook to execute custom code when a user’s role is updated, such as sending an email notification.

Sending an email to a user when their role is updated

To send an email to a user when their role is updated, we’ll create a function that uses the wp_mail function to send an email notification to the user.

function send_user_role_update_notification($user_id, $new_role, $old_roles ) {
    $user = get_userdata($user_id);
    $to = $user->user_email;
    $subject = 'Your role has been updated';
    $message = "Hello $user->display_name,\n\nYour role on our website has been updated from $old_roles to $new_role.\n\nThank you!";
    wp_mail($to, $subject, $message);
}
add_action('set_user_role', 'send_user_role_update_notification', 10, 3);
  • The send_user_role_update_notification function is our custom function that will be triggered when a user’s role is updated.
  • We use the get_userdata function to retrieve the user’s email address and display name.
  • We set the $to variable to the user’s email address.
  • We set the $subject variable to a subject line for the email.
  • We set the $message variable to the body of the email, which includes the user’s display name, old role, and new role.
  • We use the wp_mail function to send the email to the user.

Finally, we use the add_action function to add our custom function to the set_user_role action hook. This ensures that our function will be triggered whenever a user’s role is updated.

Conclusion

Sending an email to a user when their role is updated can be a helpful way to keep your users informed and up-to-date on their account status. By using the set_user_role action hook and the wp_mail function, you can easily add this functionality to your WordPress website.

Leave a Comment