I have a custom post type called coupons. All coupons contain an ACF field called 'expiration_date' which is a datepicker field. I am trying to use this field to set the post status to 'draft' after the expiration date passes. I'm not sure if I'm just not using the correct wp hook or if my code is incorrect, but its not working. Could anyone offer a suggestion? Many thanks in advance.
<?php add_action( 'save_post', 'remove_expired_coupons', 10, 2 );
function remove_expired_coupons( $post_ID, $post )
{
$expiry = new DateTime();
$expiry->setTime(0,0,0);
$expiresValue = $expiry->format('Y-m-d');
$args = array(
'post_type' => 'coupon',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'expiration_date',
'value' => $expiresValue,
'compare' => '<=',
'type' => 'DATE'
),
),
);
$posts = get_posts($args);
foreach( $posts as $post ) {
if(get_field('expiration_date', $post->ID)) {
$postdata = array(
'ID' => $post->ID,
'post_status' => 'draft'
);
wp_update_post($postdata);
}
}
}