WordPress按用户角色发送文章发布自定义通知代码报错排查求助
错误原因定位
代码存在2个核心语法错误导致角色判断逻辑完全失效,永远触发最后一个else分支发送第三种通知:
- 重复调用
get_userdata传参错误:已经通过$author = get_userdata($post->post_author)拿到了合法的用户对象,后续又将该对象作为参数传入get_userdata,而该函数仅支持传入数字类型的用户ID,最终$authorData返回false,无法正常读取用户角色。 in_array函数用法错误:in_array的标准语法为in_array(要查找的元素, 目标数组, 严格匹配开关),第一个判断中直接传入多个独立的角色字符串作为参数,语法不符合要求,该条件永远返回false。
修正后可正常运行的代码
function notifyauthor($post_id) { $post = get_post($post_id); // 单次查询获取作者用户对象 $author = get_userdata($post->post_author); // 兼容作者信息不存在的异常场景,避免报错 if (!$author) return; $subject = "文章发布通知:".$post->post_title; // 定义作者及以上权限的角色列表 $high_privilege_roles = ['author', 'postseditor', 'editor', 'administrator']; // 判断用户角色是否属于高权限组,只要匹配任意一个就符合条件 if (array_intersect($high_privilege_roles, $author->roles)) { // 作者及以上角色的通知内容 $message = " 尊敬的".$author->display_name.": 您投稿的文章《".$post->post_title."》已成功发布。 点击查看您的文章:".get_permalink( $post_id )." 其余自定义通知内容1"; } elseif (in_array('contributor', $author->roles)) { // 贡献者角色的通知内容 $message = " 尊敬的".$author->display_name.": 您投稿的文章《".$post->post_title."》已成功发布。 点击查看您的文章:".get_permalink( $post_id )." 其余自定义通知内容2"; } else { // 订阅者等低权限角色的通知内容 $message = " 尊敬的".$author->display_name.": 您投稿的文章《".$post->post_title."》已成功发布。 点击查看您的文章:".get_permalink( $post_id )." 其余自定义通知内容3"; } wp_mail($author->user_email, $subject, $message); } add_action('publish_post', 'notifyauthor');
内容的提问来源于stack exchange,提问作者Simon48
相关产品推荐
相关产品推荐

