Send a confirmation of user role upgrade conditionally

I’m using this snippet of code to send a confirmation email to user’s when their account is upgraded to a new user role.

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 sends an email whether the account has been upgraded or downgraded which doesn’t give me the flexibility of sending a different message for a downgrade. I have two situations where this is used.
  1. When a user is upgraded from “contributor” to “author”.
  2. When an “author” is downgraded to “contributor”.

How can I use conditions to send a different email for each of these events?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Quite possibly something like this might work;

    function user_role_update( $user_id, $new_role ) {
    $site_url = get_bloginfo('wpurl');
    $user_info = get_userdata( $user_id );

    if (user_can( $user_id, 'capability' ) ) {

        $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);

    } elseif (user_can( $user_id, 'capability' ) ) {

    // etc...

    }

}
add_action( 'set_user_role', 'user_role_update', 10, 2);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments