How do I send an automatic email to my WordPress users to let them know that their user role has changed?
July 31, 2017
A few weeks ago we developed a site where the client wanted multiple types of customers, each having a different discount volume. We were able to do this simply by creating a few different new user types. They also wanted an automatic email to be sent out whenever a customer type (WP user role) was changed letting their customer know. The following is the code we placed in the theme’s functions.php file to do this.
function user_role_update( $user_id, $new_role ) {
if ( $new_role == 'customer_silver' || $new_role == 'customer_gold' || $new_role == 'customer_platinum' || $new_role == 'customer_dbl_platinum' || $new_role == 'customer_dealer' ) {
$site_url = get_bloginfo('wpurl');
$user_info = get_userdata( $user_id );
$userRole = implode(', ', $user_info->roles);
$userRoleName = '';
if ($userRole == 'customer_silver') { $userRoleName = 'Silver level customer'; }
elseif ($userRole == 'customer_gold') { $userRoleName = 'Gold level customer'; }
elseif ($userRole == 'customer_platinum') { $userRoleName = 'Platinum level customer'; }
elseif ($userRole == 'customer_gdbl_platinum') { $userRoleName = 'Double Platinum level customer'; }
elseif ($userRole == 'customer_dealer') { $userRoleName = 'Dealer level customer'; }
$to = $user_info->user_email;
$subject = "Customer Level Change : ".$site_url."";
$message = "Hello " .$user_info->display_name . ". Your customer level has been changed on ".$site_url." Yyou are now a " . $userRoleName . ". Please login using the same credentials to see what has changed." . $site_url . "/my-account";
wp_mail($to, $subject, $message);
}
}
add_action( 'set_user_role', 'user_role_update', 10, 2);