WordPress中wp_mail重复发送邮件问题求助
解决WordPress删除文章时重复发送邮件的问题
这个问题其实挺常见的,核心原因在于你用的delete_post钩子在WordPress里会被触发两次:一次是文章被移至回收站时,另一次是文章被永久删除(不管是手动删除还是回收站自动清理)时。这就导致你的authorNotification函数被执行了两遍,自然会发两封一模一样的邮件。
下面给你两个靠谱的解决方案:
方案1:用更精准的钩子(推荐)
WordPress提供了细分的钩子来区分不同的删除动作,完全可以避开重复触发的问题:
trashed_post:只在文章被移到回收站时触发一次,这通常就是管理员“删除”文章的场景,正好匹配你发“文章被拒绝”通知的需求deleted_post:只在文章被永久删除时触发一次
把钩子换成trashed_post就能直接解决问题,同时我还加了一些健壮性优化:
function authorNotification($post_id) { // 跳过自动草稿和修订版,避免无意义的触发 if (get_post_status($post_id) === 'auto-draft' || wp_is_post_revision($post_id)) { return; } $post = get_post($post_id); $author = get_userdata($post->post_author); // 确保能获取到作者信息,防止出现PHP报错 if (!$author) { return; } $message = " Hi " . $author->display_name . ", We are sorry to inform you that your article, " . $post->post_title . " has been declined. We strongly recommend you to go through the guest posting guidelines before you submit an article again. "; wp_mail($author->user_email, "Declined", $message); } add_action('trashed_post', 'authorNotification');
方案2:添加重复发送防护机制
如果你因为某些原因必须使用delete_post钩子,可以通过临时缓存(transient)来限制短时间内重复发送:
function authorNotification($post_id) { // 跳过自动草稿和修订版 if (get_post_status($post_id) === 'auto-draft' || wp_is_post_revision($post_id)) { return; } // 检查该文章的通知是否已经发送过 $email_sent_key = 'declined_email_' . $post_id; if (get_transient($email_sent_key)) { return; } $post = get_post($post_id); $author = get_userdata($post->post_author); if (!$author) { return; } $message = " Hi " . $author->display_name . ", We are sorry to inform you that your article, " . $post->post_title . " has been declined. We strongly recommend you to go through the guest posting guidelines before you submit an article again. "; wp_mail($author->user_email, "Declined", $message); // 设置1小时的缓存,防止重复发送(时间可以根据需求调整) set_transient($email_sent_key, true, 3600); } add_action('delete_post', 'authorNotification');
内容的提问来源于stack exchange,提问作者Adham Mohamed
相关产品推荐
相关产品推荐

