WordPress:我需要在用户角色更改时向用户发送通知,我的代码片段不起作用

问题描述 投票:0回答:2

我正在使用 WordPress 构建一个会员风格的网站。当用户注册时,他们的默认角色是“订阅者”,一旦我们手动批准他们的帐户,我们就会将用户角色更改为“private_event_member”,我们需要向用户发送一封电子邮件,告诉他们我们已经更改了他们的角色。我找到了以下代码片段并将其添加到functions.php文件中

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

这未能按预期发送电子邮件。因此,为了确保我决定安装一个名为 WP Mail Log 的插件,然后再安装 WP Mail SMTP,我配置了 Sendblue SMTP 选项。我已经测试了此电子邮件和所有其他电子邮件,例如用户注册通知和新订单,正在发送并成功记录在日志中,这些正在被接收。然而上面提到的代码似乎什么也没做。

这似乎是一段广泛使用的代码,应该可以工作,所以任何人都可以向我解释为什么这个代码片段的行为与服务器上的其他邮件不同?据我所知,它甚至没有出现在发送日志中,它根本没有做任何事情。我正在连接的 set_user_role 操作是否已更改?可能是什么原因?

任何帮助非常感谢!

php wordpress wordpress-theming wordpress-plugin-creation email-delivery
2个回答
2
投票

您应该为此使用 profile_update 挂钩。在这里阅读更多信息 - https://developer.wordpress.org/reference/hooks/profile_update/

function notify_user_on_role_change($user_id,$old_user_data,$userdata) {
    // Getting role before update
    foreach($old_user_data->roles as $role):
        $old_role = $role;
    endforeach;

    // error_log(print_r($userdata,true)); // debug 

    //If we change role send email
    if($old_role != $userdata['role']):
        $user_info = get_userdata( $user_id );
        $to = $user_info->user_email; 
        $subject = "Profile Updated";
        $message = "Hello, your user role is changed to ".$userdata['role']."";
        wp_mail( $to, $subject, $message);
    endif;
}
add_action('profile_update','notify_user_on_role_change',10,3);

仅在您更改为特定用户角色时发送通知

function notify_user_on_role_change($user_id,$old_user_data,$userdata) {
    // Getting role before update
    foreach($old_user_data->roles as $role):
        $old_role = $role;
    endforeach;

    // error_log(print_r($old_role,true)); // debug 

    //If we change role send email
    if($old_role != 'private_event_member' && $userdata['role'] == 'private_event_member'):
        $user_info = get_userdata( $user_id );
        $to = $user_info->user_email; 
        $subject = "Profile Updated";
        $message = "Hello, your user role is changed to ".$userdata['role']."";
        wp_mail( $to, $subject, $message);
    endif;
}
add_action('profile_update','notify_user_on_role_change',10,3);

0
投票

我知道这已经晚了,但我想如果其他人遇到以下问题我会添加。我没有足够的代表来评论 MartinMirchev 的答案,所以我必须单独发布一个。

添加到他们的答案中,它没有将角色的名称放入电子邮件中,但是,我现在通过更改使其可以工作:

$message = "Hello, your user role is changed to ".$userdata['role']."";

至:

$message = "Hello, your user role is changed to ".$role."";
© www.soinside.com 2019 - 2024. All rights reserved.