Need to expire post to draft when it reaches date from ACF date-picker field. This is code I’m using:
// expire offer posts on date field.
if (!wp_next_scheduled('expire_posts')){
wp_schedule_event(time(), 'twicedaily', 'expire_posts'); // this can be hourly, twicedaily, or daily
}
add_action('expire_posts', 'expire_posts_function');
function expire_posts_function() {
$today = date('Ymd');
$args = array(
'post_type' => array('event'), // post types you want to check
'posts_per_page' => -1
);
$posts = get_posts($args);
foreach($posts as $p){
$expiredate = get_field('ev_date', $p->ID, false, false); // get the raw date from the db
if ($expiredate) {
if($expiredate < $today){
$postdata = array(
'ID' => $p->ID,
'post_status' => 'draft'
);
wp_update_post($postdata);
}
}
}
}
What I’m doing wrong? This is my field settings:
And source:
3
Answers
It looks like your trying to compare the variable
$today
(which is formatted Ymd – e.g. 20210411) with your field info stored in$expiredate
(which is formatted j.n.Y) I think you should change the Return Format on ACF to Ymd so that it matches.It is true that passing false to
get_field()
should return the field unformatted, but it appears that you’re sending too many parameters toget_field()
which should only get up to 3 parameters:I would try:
And change the ACF return format to Ymd
Convert your date format
'j.n.Y'
toYmd
.I’ve done similar and it works if you make the ACF return format to U for universal. That way time zones do not pose an issue.