I am using ACF as part of for contract management. So I have valid_until date for each contract. What I need is to calculate the remaining days of active contracts. Remaining days would be valid_until – today. I am planing to save this to a ACF field called remaining_days wit a cron job that would run every day.
I have the below code and when I run with a cron job, it saves 0 (zero).
function wpf11144133_contracts_expiry_time() {
$date_to = get_field( 'valid_until' );
$date_today = new DateTime(date('Ymd', strtotime('today')));
$date_1 = new DateTime(date('Ymd', strtotime($date_to)));
$date_2 = new DateTime(date('Ymd', strtotime($date_today)));
$days = $date_1->diff($date_2)->days ;
$posts = get_posts( array(
'post_type' => 'contract',
'post_status' => 'publish',
'posts_per_page' => -1,
'no_found_rows' => true,
'update_cache' => false,
'meta_query' => array(
array(
'key' => 'status',
'value' => 'Valid',
'compare' => '=',
)
),
) );
if( ! empty ( $posts ) ) {
foreach( $posts as $post ) {
update_field('remaining_days', $days, $post->ID);
}
}
}
add_action( 'wpf11144133_contracts_expiry_time_calculation_job', 'wpf11144133_contracts_expiry_time' );