您需要使用{old_status}to{new_status} hook. 和使用draft
和publish
状态。只有当您的帖子状态从draft
到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\' );
请记住,如果您将职位状态更改回
draft
再次发送给
publish
将再次发送电子邮件。为了防止出现这种情况,您可以更新post meta,它会告诉您是否已经发送了电子邮件。
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\' );