krishna89 krishna89 - 4 months ago 24
PHP Question

wordpress - wp insert post hook for only new posts saved

I am using

wp insert post
as a hook to send an email when ever a new post has been submitted in wordpress, I have taken the reference of this link and tried below code. I am able to get emails perfectly, the problem is I am receiving mails even when the post is trashed which is not required. Is there any way to trigger mail only when new post is created and not for any other actions.

function my_project_updated_send_email( $post_id, $post, $update ) {

// If this is a revision, don't send the email.
if ( wp_is_post_revision( $post_id ) )

$post_url = get_permalink( $post_id );
$subject = 'A post has been updated';

$message = "A post has been updated on your website:\n\n";
$message .= $post->post_title . ": " . $post_url;

// Send email to admin.
wp_mail( '', $subject, $message );
add_action( 'wp_insert_post', 'my_project_updated_send_email', 10, 3 );


I just figured it out just after posting this question, but updating my solution here so that it would be useful for some one.

The solution is I have added a checkpoint by checking the post_status of submitted post using the same wp insert post like below.

$post_status = get_post($post_id)->post_status;

if($post_status == 'pending'){
//send the post pending email
}elseif($post_status == 'publish'){
// send the post published email
}elseif($post_status == 'trash'){
// send the post trashed email