wordpress - 当用户的帖子在 WordPress 中发布时向用户发送电子邮件通知。为什么多次?
问题描述
我有一个 WordPress 网站,用户可以从前端发帖,发帖状态为草稿。
现在,当我从管理面板发布帖子时,通知电子邮件会发送不止一次。我需要发送一次电子邮件。
在我的代码下面:
if (is_admin()) {
function notifyauthor($post_id) {
$post = get_post($post_id);
$author = get_userdata($post->post_author);
$subject = "Post publish notification";
$headers = 'From: '.get_bloginfo( 'name' ).' <my_email@gmail.com>' . "\r\n";
$message = "
Hi ".$author->display_name.",
Your post, \"".$post->post_title."\" has just been published.
View post: ".get_permalink( $post_id )."
Thank You, Admin"
;
wp_mail($author->user_email, $subject, $message, $headers);
}
add_action('publish_post', 'notifyauthor');
}
我试过current_user_can('administrator')
了is_admin()
,但我得到了同样的结果。
解决方案
许多钩子实际上会运行不止一次。简单的解决方案是在第一次迭代后通过 post_meta 的方式添加一个计数器,然后检查它不存在。这未经测试,但应该可以工作。
function notifyauthor($post_id) {
if (is_admin() && !(metadata_exists('post', $post_id, 'sent_notification_email'))) {
$post = get_post($post_id);
$author = get_userdata($post->post_author);
$subject = "Post publish notification";
$headers = 'From: '.get_bloginfo( 'name' ).' <my_email@gmail.com>' . "\r\n";
$message = "
Hi ".$author->display_name.",
Your post, \"".$post->post_title."\" has just been published.
View post: ".get_permalink( $post_id )."
Thank You, Admin";
wp_mail($author->user_email, $subject, $message, $headers);
// Set a meta key as a counter
update_post_meta($post_id, 'sent_notification_email', '1');
}
}
add_action('publish_post', 'notifyauthor');
推荐阅读
- php - 一个请求的多个模型或数据库?
- swiftui - 为什么导航栏中的 SwiftUI TextField 一次只接受输入一个字符
- android - 在 mvvm 模式中获取 MainActivity 参考
- postgresql - 每个 SQL 子查询
- leaflet - 绑定新图层单击功能后,Leaflet-geoman 删除按钮不起作用
- python-3.x - Python 3 OOP 将方法重定向到属性的方法
- java - 将 JButton 放在 JFrame 内的 JPanel 内,结果可变
- python - 图像未使用 django 从数据库加载到网页上
- typescript - TS2307 - 如何在 Angular 9 中使用我自己的库?
- java - 有没有办法以字符串格式从 XML 文件中获取查询?