仅在发布后通知用户

时间:2020-05-11 作者:JoaMika

我正在使用此功能在用户的帖子发布时通知用户。然而,更新帖子时会重复发送电子邮件。我只想在第一次发布帖子时发送一封电子邮件,如果帖子随后更新,我不会再发送更多电子邮件。

function notifyauthor($post_id) {

$post = get_post($post_id);
$author = get_userdata($post->post_author);
$subject = "Post Published: ".$post->post_title."";

$message = "
      Hi ".$author->display_name.",

      Your post, \\"".$post->post_title."\\" has just been published.

      View post: ".get_permalink( $post_id )."

      "
      ;

   wp_mail($author->user_email, $subject, $message);
}
add_action(\'publish_post\', \'notifyauthor\');

2 个回复
最合适的回答,由SO网友:WebElaine 整理而成

您可以使用transition_post_status 钩子,因为它已经知道帖子的当前和以前的状态。

<?php
add_action(\'transition_post_status\', \'wpse_366380_email_on_publish\', 10, 3);
function wpse_366380_email_on_publish( $new_status, $old_status, $post ) {
    // Only if this post was just published, and previously it was either
    // "auto-draft" (brand new) or "pending" (not yet published)
    if ( \'publish\' == $new_status && ( \'auto-draft\' == $old_status || \'pending\' == $old_status ) ) {
        $post = get_post($post_id);
        $author = get_userdata($post->post_author);
        $subject = "Post Published: ".$post->post_title."";
        $message = "Hi ".$author->display_name.",
        Your post, \\"".$post->post_title."\\" has just been published.
        View post: ".get_permalink( $post_id )."";
        wp_mail($author->user_email, $subject, $message);
    }
}
?>

SO网友:made2popular

您已经使用了“publish\\u post”挂钩,当一篇文章第一次从其他内容转换到该状态时,以及在后续的文章更新时(旧的和新的状态都相同),它都会触发。

相反,您应该使用“transition\\u post\\u status”挂钩。当帖子从一种状态转换到另一种状态时,它会触发。您可以在此处了解更多信息:https://developer.wordpress.org/reference/hooks/transition_post_status/

还可以查看以下示例代码: function wpdocs_run_on_publish_only( $new_status, $old_status, $post ) { if ( ( \'publish\' === $new_status && \'publish\' !== $old_status ) && \'my-custom-post-type\' === $post->post_type ) { // do stuff } } add_action( \'transition_post_status\', \'wpdocs_run_on_publish_only\', 10, 3 );