I have a Custom Post Type named Task. I created a function that sends an email to the selected Agent, notifying a new task has been assigned. Here is the function:
function real_estate_send_mail_to_agent() {
global $post;
// If this is just a revision, don't send the email.
if ( wp_is_post_revision( $post->ID ) ) {
return;
}
// Exit function if post type is not equal to task
if ( $post->post_type !== 'task' ) {
return;
}
// Email header
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Recipient
$agent = get_field_object("agent", $post->ID);// Get agent object from user_table
$emailTo = (string) $agent['value']['user_email']; // Get agent email
$agent_display_name = $agent['value']['display_name']; // Get agent display name
// Email Subject
$subject = "New Task: " .wp_strip_all_tags(get_the_title($post->ID));;
// Email Body
$message = "Hi <b>".$agent_display_name."</b><br/>"
$message .= "You have been assigned a new task <br/>";
$message .= "Please have a look at it ".get_permalink( $post->ID );
// Send the mail
wp_mail( $emailTo, $subject, $message, $headers );
}
add_action('save_post', 'real_estate_send_mail_to_agent', 11);
The function sends the email to the agent which is fine. The issue is that it triggers even when the post is updated or move to trash.
I want it to fire only when a new post is created using the save_post. The reason I need to use save_post is because I have to get the agent email from the user object in the User Field Type using the ACF plugin. If I use publish_post, the email is not sent, since it can’t fetch the agent email. Help please.