'Wordpress - set post to draft by date-picker custom field
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:
Solution 1:[1]
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);
}
}
}
}
Solution 2:[2]
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
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bhautik |
| Solution 2 | Hillel |
| Solution 3 | jimmyfrank |

