Notify a WordPress User when their Role has Been Changed to a Specific Role
I found this nifty code over on WPSnipp.com. Essentially, it forces WordPress to send an email to a user anytime their role is changed. Or more accurately, anytime their role is set. The problem with that is simple: when a user is created, their role is set. So they receive an email (two actually, in my testing) notifying them of this, which is a bit redundant given that they’ve likely already received the new user notification email that WP sends by default.
I only want to notify a user if their role has been changed from something other than Subscriber. In the example below, we’ll notify them if they’ve been bumped up to a Contributor.
Here’s the modified code:
function user_role_update( $user_id, $new_role ) {
if ($new_role == 'contributor') {
$site_url = get_bloginfo('wpurl');
$user_info = get_userdata( $user_id );
$to = $user_info->user_email;
$subject = "Role changed: ".$site_url."";
$message = "Hello " .$user_info->display_name . " your role has changed on ".$site_url.", congratulations you are now an " . $new_role;
wp_mail($to, $subject, $message);
}
}
add_action( 'set_user_role', 'user_role_update', 10, 2);
The key change I made is if ($new_role == 'contributor')
. You could change contributor to any other role (ie, author, editor, administrator or any custom role). If you want to notify users whenever they’ve been changed from subscriber to any other role, change that line to this:
if ($new_role != 'subscriber') {
Up Next: Allow WordPress Authors to Delete their Posts from the Front End