You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress后台发布用户投稿时重复发送通知邮件如何解决

问题原因

  • publish_post 钩子的触发机制是文章处于发布状态时每次执行保存操作都会触发,不止首次从草稿转发布的节点,你后续编辑已发布的投稿、系统自动保存修订版本都会触发该钩子执行发信逻辑
  • 原代码没有做发信状态校验,每次钩子触发都会执行发信操作,自然会出现重复发信的问题

修复方案

我们可以通过「状态跃迁校验 + 发信标记存储」的逻辑,保证仅首次将草稿投稿转为发布状态时发一次通知,修改后的代码如下:

if (is_admin()) {
    function notifyauthor($post_id) { 
        // 跳过文章修订版本
        if (wp_is_post_revision($post_id)) {
            return;
        }
        
        // 校验是否已经发送过通知,发过直接终止
        $notification_sent = get_post_meta($post_id, 'author_notification_sent', true);
        if ($notification_sent == 1) {
            return;
        }

        $post = get_post($post_id);
        // 仅当文章是从草稿转为发布状态时才执行发信
        if ($post->post_status != 'publish' || get_post_meta($post_id, '_old_post_status', true) != 'draft') {
            return;
        }

        $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"
            ;
            
        if (wp_mail($author->user_email, $subject, $message, $headers)) {
            // 发信成功后标记已发送,避免后续重复触发
            update_post_meta($post_id, 'author_notification_sent', 1);
        }
    }
    // 提前存储文章更新前的状态,用于判断状态跃迁
    function save_old_post_status($post_id) {
        if (wp_is_post_revision($post_id)) {
            return;
        }
        $post = get_post($post_id);
        update_post_meta($post_id, '_old_post_status', $post->post_status);
    }
    add_action('pre_post_update', 'save_old_post_status');
    add_action('publish_post', 'notifyauthor');
}

逻辑说明

  • 新增pre_post_update钩子提前存储文章更新前的状态,只有状态从draft变为publish的草稿投稿才会触发通知
  • 新增发信标记author_notification_sent,发信成功后写入文章自定义字段,后续所有触发publish_post钩子的操作都会直接跳过发信逻辑
  • 跳过修订版本的触发请求,避免自动保存等系统操作导致的误发

内容的提问来源于stack exchange,提问作者Aminul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:09:00