You can use the transition_post_status
hook, which is fired whenever the status is changed. So to perform an action when the status is changed to publish
, you’d do this:
function notificationApprove( $new_status, $old_status, $post ) {
if ( 'publish' === $new_status && 'publish' !== $old_status && 'post' === $post->post_type ) {
// Send mail
}
}
add_action( 'transition_post_status', 'notificationApprove', 10, 3 );
This will only fire when the status changes. This means that if the post is ever unpublished and then republished the notification will be sent again.
If you only ever what the notification to be sent once, then you could save a custom field when the notification is sent, then when the post is re-published check if the field already exists and don’t send the notification if it does:
function notificationApprove( $new_status, $old_status, $post ) {
if ( 'publish' === $new_status && 'publish' !== $old_status && 'post' === $post->post_type ) {
$notification_sent = get_post_meta( $post->ID, 'notification_sent', true );
if ( $notification_sent !== 'sent' ) {
// Send mail
update_post_meta( $post->ID, 'notification_sent', 'sent' );
}
}
}
add_action( 'transition_post_status', 'notificationApprove', 10, 3 );