John Davidson

php - WordPress: I need to send users a notification when their role is changed, my code snippet doesn't work

0 comments
Message:


I'm building a members style site using WordPress. When a user registers their default role is "subscriber" once we manually approve their account we change the user role to "private_event_member", we need to send the user an email to tell them we have changed their role. I found the following code snippet and added it to the functions.php file


function user_role_update( $user_id, $new_role ) {
$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);

This failed to send the email as expected. So to be sure I decided to install a plugin called WP Mail Log and then also WP Mail SMTP, I configured the Sendblue SMTP option. I've tested this and all other emails like for example user registration notifications and new orders are being sent and recorded successfully in the logs, these are being received. The above mentioned code however seems to do nothing.


This seems to be a widely used piece of code that should work so can anyone explain to me why this snippet behaves differently from other mail on the server? It doesn't even appear in the sending logs so as far as I can see it's not doing anything at all. Has the set_user_role action I'm hooking into changed? What could be the cause?


Any help much appreciate!



My Answer:
would look something like this:

php
function notify_user_role_change( $user_id, $new_role ) {
$user_info = get_userdata( $user_id );
$user_email = $user_info->user_email;
$subject = 'Your role has been changed';
$message = 'Your role has been changed to ' . $new_role;

wp_mail( $user_email, $subject, $message );
}

add_action( 'set_user_role', 'notify_user_role_change', 10, 2 );


This code snippet creates a function `notify_user_role_change` that sends an email notification to the user when their role is changed. It uses the `wp_mail` function to send the email with the user's email address, a subject line, and a message indicating their new role.

The `add_action` function hooks this function to the `set_user_role` action, which is triggered when a user's role is changed. The function takes two parameters: the user ID and the new role.

Rate this post

4 of 5 based on 2918 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us