The code below sends out an email every time I (change the STATUS field and then) safe/update the post. But it’s not working the way I want and I know whats’s wrong:
The field updates are always saved AFTER the post is saved so it always sends out the PREVIOUS field values (its like I’m always 1 step behind).
How can I let the POST UPDATE come LAST so that the then triggered action (send email) will have the latest field values included?
function yl_send_booking_email_after_post_update( $new_status, $old_status, $post ) {
if ( $new_status == $old_status ) {
if ( 'booking' === get_post_type() ) { // check the custom post type
$send_email = get_post_meta( $post->ID, 'bookings_field_send_email', true );
if ( $send_email === 'yes' ) {
$status = get_post_meta( $post->ID, 'bookings_field_status', true );
if ( $status === 'confirmed' ) {
$subject = get_post_meta( $post->ID, 'bookings_field_email_title_confirmed', true );
} else if ( $status === 'changed' ) {
$subject = get_post_meta( $post->ID, 'bookings_field_email_title_changed', true );
} else if ( $status === 'canceled by guest' ) {
$subject = get_post_meta( $post->ID, 'bookings_field_email_title_canceled_by_guest', true );
} else {
$subject = get_post_meta( $post->ID, 'bookings_field_email_title_canceled_by_us', true );
}
if ( $status === 'confirmed' ) {
$body = get_post_meta( $post->ID, 'bookings_field_email_content_confirmed', true );
} else if ( $status === 'changed' ) {
$body = get_post_meta( $post->ID, 'bookings_field_email_content_changed', true );
} else if ( $status === 'canceled by guest' ) {
$body = get_post_meta( $post->ID, 'bookings_field_email_content_canceled_by_guest', true );
} else {
$body = get_post_meta( $post->ID, 'bookings_field_email_content_canceled_by_us', true );
}
$to = get_post_meta( $post->ID, 'bookings_field_email', true );
$headers = array
(
'From: ' . get_bloginfo('name') . ' <' . get_bloginfo('admin_email') . '>',
'Bcc: ' . get_bloginfo('admin_email'),
'X-Mailer: PHP/' . phpversion(),
'MIME-Version: 1.0',
'Content-type: text/html; charset=iso-8859-1'
);
$headers = implode( "\r\n" , $headers );
wp_mail( $to, $subject, $body, $headers );
}
}
}
}
add_action( 'transition_post_status', 'yl_send_booking_email_after_post_update', 15, 3 );