在发布和更新后发送电子邮件给Wordpress用户

时间:2015-02-05 17:35:40

标签: wordpress email post

我已设法在使用transition_post_status发布帖子时向用户发送电子邮件,但在帖子更新时不会发送。我尝试过将old_status和new_status都使用'new',但没有运气。任何方向都非常感谢。到目前为止,我的参考文献来自https://wordpress.stackexchange.com/questions/100644/how-to-auto-send-email-when-publishing-a-custom-post-type?rq=1

add_action('transition_post_status', 'send_media_emails', 10, 3);
function send_media_emails($new_status, $old_status, $post){
     if ( 'publish' !== $new_status or 'publish' === $old_status)
        return;

        $the_media = get_users( array ( 'role' => 'media' ) );
        $emails = array ();

        foreach($the_media as $media)
            $emails[] = $media->user_email;

        $body = sprintf('There are new bus cancellations or delays in Huron-Perth <%s>', get_permalink($post));

        wp_mail($emails, 'New Bus Cancellation or Delay', $body);

}

//正在工作,但现在发送双重电子邮件。我尝试将其全部包装在函数中,但这也无效。只是把它放在哪里感到困惑。

 function send_media_emails($post_id){

$the_media = get_users( array ( 'role' => 'media' ) );
$emails = array ();

if( ! ( wp_is_post_revision( $post_id) && wp_is_post_autosave( $post_id ) ) ) { 
        return;
    }
if(get_post_status($post_id) == 'draft' or get_post_status($post_id) == 'pending' or get_post_status($post_id) == 'trash'){
        return;
        }
foreach($the_media as $media){
        $emails = $media->user_email;
    }
    $body = sprintf('There are new bus cancellations or delays in Huron-Perth <%s>', get_permalink($post_id));

    wp_mail($emails, 'New Bus Cancellation or Delay', $body);   

}
add_action('post_updated', 'send_media_emails');

2 个答案:

答案 0 :(得分:1)

transition_post_status挂钩仅在帖子状态发生变化时触发,例如来自&#39;草案&#39;发布&#39;。

更好的钩子是post_updated。这会触发所有更新,因此您需要过滤掉脚本中草稿和评论的更新。

可能能够执行'publish_to_publish'操作,但我还没有对此进行过个人测试。

答案 1 :(得分:0)

更新帖子(例如,发布>发布)时,transition_post_status也将触发。

但是,一个已知的错误使transition_post_status有时触发两次:https://github.com/WordPress/gutenberg/issues/15094

有一个解决方案,可以从那里复制两次transition_post_status:

function ghi15094_my_updater( $new_status, $old_status, $post ) {
    // run your code but do NOT count on $_POST data being available here!
}

function ghi15094_transition_action( $new_status, $old_status, $post ) {
    if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) { 
        ghi15094_my_updater( $new_status, $old_status, $post );
        set_transient( 'my_updater_flag', 'done', 10 );
    } else {
        if ( false === get_transient( 'my_updater_flag' ) ) {
            ghi15094_my_updater( $new_status, $old_status, $post );
        }
    }
}
add_action( 'transition_post_status', 'ghi15094_transition_action', 10, 3 );