I’m having trouble with my WordPress site. I want to automatically send an email to users when an admin changes their account from “pending” to “expert” status. The user already gets a waiting notification from a different plugin, but they should get another email once approved.
Here’s what I’m trying:
add_action('user_profile_update_errors','account_approval_email',10,3);
function account_approval_email($member_id,$previous_data,$current_data) {
foreach($previous_data->roles as $user_role):
$previous_role = $user_role;
endforeach;
$target_roles = array('expert');
if( $previous_role == 'pending' && in_array($current_data['role'],$target_roles ) ):
$member_info = get_userdata( $member_id );
$recipient = $member_info->user_email;
$email_subject = "Your Expert Account is Ready";
$email_body = 'Hello! Great news. Your expert account has been activated.
{member_info}
Support Team';
wp_mail($recipient, $email_subject, $email_body);
endif;
}
The code runs without errors but no email gets delivered. What am I missing here?
You’re using the wrong hook. user_profile_update_errors is for validation and error handling during profile updates, not for triggering actions after successful updates. This hook fires before the actual update happens, so your role comparison logic won’t work. Switch to profile_update instead - it fires after the user data has been successfully updated. Also, you’re accessing the role data incorrectly. The $current_data parameter doesn’t contain a ‘role’ key in the format you’re expecting. Here’s the fix: php add_action('profile_update', 'account_approval_email', 10, 2); function account_approval_email($user_id, $old_user_data) { $user = get_userdata($user_id); $old_roles = $old_user_data->roles; $new_roles = $user->roles; if (in_array('pending', $old_roles) && in_array('expert', $new_roles)) { // Your email logic here } } This’ll fix your email delivery issue since the hook fires at the right time with properly accessible user data.
check your wordpress debug log first - it might be throwing silent errors. that hook looks wrong to me too, but you’re also not sanitizing the email content properly. add some basic debugging like error_log('email function triggered'); to see if it’s even firing. could be a plugin conflict since you mentioned another plugin already handles notifications.
It’s probably your WordPress email setup, not your code. WordPress uses the server’s default mail function, which breaks constantly on shared hosting. I’ve dealt with this before - emails get sent but die in spam folders or never leave the server. Get WP Mail SMTP or Easy WP SMTP and use a real mail service instead of PHP’s mail function. Throw some error_log statements before and after your wp_mail call to see if your code’s even running. Some hosts just disable mail completely for security. Check your hosting panel or ask support if mail works. Once you’ve got proper SMTP running, your emails will actually deliver.