Email Post Attachment on wp_insert_post Action

After asking this question in several places and not getting a solution, I found the solution this morning myself.

Instead of hooking the function send_email_on_pending_post_creation to the “wp_insert_post” action, you need to hook it to the “add_attachment” action which occurs AFTER the post is inserted and when the attachment is added to the post. You also need to update the code in the send_email_on_pending_post_creation function to fetch the post_parent (the parent post ID to which the attachment is attached) so that the post_title, post_url and post_content variables return the correct values.

Here is the updated send_email_on_pending_post_creation function which sends an email to the admin with an attachment link.

add_action('add_attachment', 'send_email_on_pending_post_creation' );

function send_email_on_pending_post_creation( $post_id ){
$attachment = get_post($post_id);
$attachment_title = get_the_title($post_id);

$parent_id = $attachment->post_parent;

$post_title = get_the_title( $parent_id );
$post_url = get_permalink( $parent_id );
$post_content = get_post_field('post_content', $parent_id);

$subject="New post pending!";

$attachments = wp_get_attachment_url($post_id);

$message = "A new post is pending on the website:";
$message .= "<br><br>";
$message .= "<strong>Post Title: </strong>";
$message .= "<a href="" . $post_url . "">" .$post_title. "</a>";
$message .= "<br><br>";
$message .= "<strong>Post Content:</strong><br>";
$message .= $post_content;
$message .= "<br><br>";
$message .= "<strong>Attachment:</strong><br><br>";
$message .= "<a href="". $attachments . "" title="". $attachment_title . "">" . $attachment_title . "</a>";
$message .= "<br><br>";

$msg_headers = array('Content-Type: text/html; charset=UTF-8', 'From: "Website" < [email protected] >');

//send email to admin
wp_mail( '[email protected]', $subject, $message, $msg_headers, $attachments );
}

Hope it helps somebody!