I have a custom field named "fecha_borrado". The date is a date picker from Advanced Custom Field.
I have this code but don't work. Maybe i did some wrong?
I added too define('ALTERNATE_WP_CRON', true); in my wp-config file
// expire offer posts on date field.
if (!wp_next_scheduled('expire_posts')){
wp_schedule_event(time(), 'hourly', '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('post'), // post types you want to check
'posts_per_page' => -1
);
$posts = get_posts($args);
foreach($posts as $p){
$expiredate = get_field('fecha_borrado', $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);
}
}
}
}
if ( "2024/01/01" < "2025/01/01" ) {
doesn't work. The reason some code can do this is because it's handling dates as numbers e.g. seconds since the Unix epoch, not as strings. The code in your question won't scale anyway, it's easier and simpler to do this usingmeta_query
so that MySQL does the date comparison, and to avoid settingposts_per_page
to -1 as it means this feature will break once you publish more than a few hundred posts. You might also want to specify the published post status explicitly