Need to set 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);
}
}
}
}
It is not working. What I'm doing wrong? This is my field settings:
And source: ACF forum
Need to set 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);
}
}
}
}
It is not working. What I'm doing wrong? This is my field settings:
And source: ACF forum
ACF saves the value as Ymd
format in database regardless of display and return format. All you need is a meta query to fetch the correct posts.
function expire_posts_function() {
//Get Expired Posts only
$expired_posts = get_posts(arrasy(
'post_type' => 'event',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'ev_date',
'value' => date('Ymd'),
'compare' => '<',
),
),
));
//Loop through the posts and set status
if ( $expired_posts ) {
foreach( $expired_posts as $expired_post ) {
wp_insert_post(array(
'ID' => $expired_post->ID,
'post_status' => 'draft',
));
}
}
}