首页 > 解决方案 > 当用户的帖子在 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(),但我得到了同样的结果。

标签: wordpress

解决方案


许多钩子实际上会运行不止一次。简单的解决方案是在第一次迭代后通过 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');

推荐阅读