Igor – could you provide your code? According to the codex here: https://codex.wordpress.org/Plugin_API/Action_Reference/set_user_role the action is definitely supposed to fire every time.
This relies on the WP_User::set_role() method here: https://core.trac.wordpress.org/browser/tags/4.4.2/src/wp-includes/class-wp-user.php#L566
Note: Please use a gist if it’s a large amount of code.
Thank you very much for reply Jerry. Here’s the code:
function notify_approved_user_login( $user_id, $new_role ) {
if ( $new_role == 'subscriber' ) {
// Reset password so we can send it out
$password = wp_generate_password( 12, false );
wp_set_password( $password, $user_id );
$user_info = get_userdata( $user_id );
$blogname = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
$message = sprintf(__("Dear %s"), $user_info->first_name) . "\r\n\r\n";
$message .= "Your account has now been activated." . "\r\n";
$message .= sprintf(__("New role: %s"), $new_role) . "\r\n";
$message .= sprintf(__("User ID: %d"), $user_id) . "\r\n";
$message .= "Welcome! Your login details are as follows:" . "\r\n";
$message .= sprintf(__("Username: %s"), $user_info->user_login) . "\r\n";
$message .= sprintf(__("Password: %s"), $password) . "\r\n";
$message .= wp_login_url() . "\r\n";
wp_mail( $user_info->user_email, sprintf(__("[%s] Your account has been activated"), $blogname), $message );
}
}
add_action('set_user_role', 'notify_approved_user_login', 10, 2);
As you can see, I tried to use ‘if’ to compare what kind of role was set but it’s not working at all. Without ‘if’ it’s working only as described in my original message.
Many thanks.
Okay I did a quick test and I’m not having a problem getting the $new_role by using normal means ( creating a user in the wp-admin and swapping roles ).
Every time I change the role, I still get a role value for $new_role.
So, that brings to light more questions. What are you doing outside of standard user manipulation in the wp-admin? This block of code isn’t your problem, it’s somewhere else.
If you’re transitioning the user’s role somewhere else that might be it, and if so, paste the code?
Thank you very much for testing Jerry.
Well, I use Pods plugin because I need custom fields in user profile and also Members plugin to define custom roles. Maybe one of those things is causing this issue.
I will try to disable them and see what happens.
It’s caused by Members plugin which allows you to assign multiple roles to each user. Without it everything works as it should.
Really strange, I will contact the support of this plugin how to solve this.
Jerry, thank you again for helping me finding the issue. I really appreciate it.
Sweet, glad I could help – sounds like they’re not using WP_User::set_role(), they may be updating the user meta directly, in which case your hook wouldn’t work.
Good luck