1

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');

1 Answer 1

1

Since you already mentioned that you are using these codes, I assume they both work for you. Now, I have combined them for you into a single function that updates the metadata after a post is published:

function set_date_difference($post_id){
    // Get the value of the first field
    $date1 = get_field('date_start', $post_id, false );
    $date1 = new DateTime( $date1 );
    $unix1 = strtotime( $date1->format( 'Y-m-d' ) );
    // Get the value of the second field
    $date2 = get_field( 'date_dun', $post_id, false );
    $date2 = new DateTime( $date2 );
    $unix2 = strtotime( $date2->format( 'Y-m-d' ) );
    // Calculate the difference 
    if( 0 === ( $unix1 - $unix2 ) ) {
        $days = 0;
    } elseif( $unix2 < $unix1 ) {
        $days = -1 * ( intval( $unix1 - $unix2 ) / DAY_IN_SECONDS );
    } else {
        $days = ( intval( $unix2 - $unix1 ) / DAY_IN_SECONDS );
    }
    // Update the field
    update_post_meta($post_id,'difference', $days);       
}
add_action('save_post','set_date_difference');

The save_post action passes the post's ID to the function, so you can use it to get and update the fields.

3
  • Hi Jack, that looks very close thanks, one concern if unix 2 is less than unix 1 it wont always be -1 - as the value is dynamic it could -2, -3 etc - have you countered for that in your code above? Commented Jun 18, 2017 at 11:03
  • @joelybristol Hi! I multiplied the value by -1 to achieve the negative value. It's not always set to -1.
    – Johansson
    Commented Jun 18, 2017 at 11:07
  • Thanks jack, will give a shot later on and let ya know how I get on. Commented Jun 18, 2017 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.