You need to use {old_status}to{new_status} hook. And use draft
and publish
statuses. This hook will only be executed when your post will change status from draft
to publish
.
function wpse_288250_send_email( $post ) {
$post_id = $post->ID;
if( wp_is_post_revision( $post_id ) ) {
return;
}
$post_url = get_permalink( $post_id );
$subject="Your post is published!";
$message = "Testing!";
$message .= "<a href="". $post_url. "">Click here to view</a>";
$email = get_post_meta($post_id, 'author_email', true );
wp_mail($email, $subject, $message );
}
add_action( 'draft_to_publish', 'wpse_288250_send_email' );
Keep in mind if you change your post status back to draft
and again to publish
e-mail will be send again. To prevent this you can update post meta which will tell you if e-mail was already sent.
function wpse_288250_send_email_once( $post ) {
$post_id = $post->ID;
if( wp_is_post_revision( $post_id ) ) {
return;
}
$email_sent = get_post_meta( $post_id, 'email_sent' );
if( $email_sent ) {
return;
}
$post_url = get_permalink( $post_id );
$subject="Your post is published!";
$message = "Testing!";
$message .= "<a href="". $post_url. "">Click here to view</a>";
$email = get_post_meta($post_id, 'author_email', true );
wp_mail($email, $subject, $message );
update_post_meta( $post_id, 'email_sent', true );
}
add_action( 'draft_to_publish', 'wpse_288250_send_email_once' );