在 Post 发布和更新时向 Wordpress 用户发送电子邮件

Send Emails to Wordpress Users on Post Publish and Update

当 post 使用 transition_post_status 发布时,我成功地向用户发送了一封电子邮件,但当 post 更新时,它没有发送。我曾尝试将 'new' 与 old_status 和 new_status 一起使用,但没有成功。非常感谢任何方向。到目前为止,我的参考资料来自 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');

transition_post_status 钩子仅在 post 状态改变时触发,例如从 'Draft' 到 'Publish'.

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

可能能够执行'publish_to_publish'操作,但我没有亲自测试过。

transition_post_status 也会在更新 post 时触发(例如发布 > 发布)。

然而,一个已知的错误使得 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 );