I am using this function to notify users when their post is published. However, repeated emails are being sent when the post is updated. I only want to send 1 email when the post is published first and then not sent more emails if the post is subsequently updated.

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');
有帮助吗?

解决方案

You could use the transition_post_status hook instead, as it already knows what the current and previous status of the post are.

<?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);
    }
}
?>

其他提示

You have used "publish_post" hook, it will fire both when a post is first transitioned to that status from something else, as well as upon subsequent post updates (old and new status are both the same).

Instead you should use "transition_post_status" hook. It fires when a post is transitioned from one status to another. You can learn more about it here: https://developer.wordpress.org/reference/hooks/transition_post_status/

Also look at this sample code: 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 );

许可以下: CC-BY-SA归因
scroll top