I have this code which is displaying the difference in days between two custom fields
<div class="distance">
<?php
$date1 = get_field( 'date_start', false, false );
$date1 = new DateTime( $date1 );
$unix1 = strtotime( $date1->format( 'Y-m-d' ) );
$date2 = get_field( 'date_dun', false, false );
$date2 = new DateTime( $date2 );
$unix2 = strtotime( $date2->format( 'Y-m-d' ) );
if( 0 === ( $unix1 - $unix2 ) ) {
echo '0';
} elseif( $unix2 < $unix1 ) {
$days = ( intval( $unix1 - $unix2 ) / DAY_IN_SECONDS );
echo '-' . $days;
} else {
$days = ( intval( $unix2 - $unix1 ) / DAY_IN_SECONDS );
echo $days;
}
?>
</div>
What I'm trying to do is that when a post is saved I add the value of the above output as the value of the 'difference' custom field using the save_post action wordpress provides using something like below
function set_date_difference($post_id){
$countdays = (the output of the above code)
update_post_meta($post_id,'difference', $countdays);
}
add_action('save_post_event','set_date_difference');