Reputation: 518
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:
Upvotes: 0
Views: 1198
Reputation: 1
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.
Upvotes: 0
Reputation: 11282
Convert your date format 'j.n.Y'
to Ymd
.
// 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 = date( 'Ymd', strtotime( get_field( 'ev_date', $p->ID ) ) ); // get the raw date from the db
if ($expiredate) {
if($expiredate < $today){
$postdata = array(
'ID' => $p->ID,
'post_status' => 'draft'
);
wp_update_post($postdata);
}
}
}
}
Upvotes: 1
Reputation: 929
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 to get_field()
which should only get up to 3 parameters:
get_field($selector, [$post_id], [$format_value]);
I would try:
$expiredate = get_field('ev_date', $p->ID);
And change the ACF return format to Ymd
Upvotes: 0