WordPress cron job to check and update post_meta

Setup: I have a custom post type ('place') that have a meta field: 'highlight' (DateTime) which is the time that the highlight feature expires. Goal: Once the highlight time has passed (expiry < now), update the post meta (highlight = NULL) Here is my code: function jj_feaurecheck_cron_function( ) { global $post; $args = array( 'post_type' => 'place', 'posts_per_page' => -1, ); $listings = get_posts( $args ); foreach($listings as $post) : setup_postdata($post); $today = date( 'Ymd' ); $expire = get_post_meta($post->ID, 'highlight', true); $today = new DateTime(); $expire_date = new DateTime($expire); //convert dates to seconds for easier comparison $expire_secs = $expire_date->format('U'); $today_secs = $today->format('U'); if ( $expire_secs < $today_secs ) : update_post_meta($post->ID, 'highlight', '' ); endif; endforeach; } add_action( 'jj_feaurecheck_cron', 'jj_feaurecheck_cron_function' ); function dg_cron_schedule_check_posts() { $timestamp = wp_next_scheduled( 'jj_feaurecheck_cron' ); if ( $timestamp == false ) { wp_schedule_event( time(), 'every_minute', 'jj_feaurecheck_cron' ); } } add_action( 'init', 'dg_cron_schedule_check_posts' ); Added this in theme functions.php checked the "date" part of the code on the actual site and it works $expire_secs < $today_secs etc... checked through WP Cron control and the cron is firing... but the posts are not updating..

Comment (1)

Jese Leos

August 10, 2024

Verified user

Unless you absolutely need to, you can store the highlight time as YYYY-mm-dd HH:mm:ss (e.g. 2024-07-24 15:01:00) and do the following: function jj_feaurecheck_cron_function( ) { global $post; $args = array( 'post_type' => 'place', 'posts_per_page' => -1, 'meta_query' => [[ 'key' => 'highlight', 'compare' => '<=', 'value' => date('Y-m-d H:i:s'), 'type' => 'DATETIME' ]] ); $listings = get_posts( $args ); foreach($listings as $post) : update_post_meta($post->ID, 'highlight', '' ); endforeach; } The meta_query will do the comparison and only return posts where the highlight meta value is in the past, allowing you to simply clear the value. It may be worth deleting the meta instead of clearing it, as it's highly likely that Wordpress/SQL will treat an empty value as less than today's date/time and will return those posts each time. Edit: To compare based on the original epoch timestamps function jj_feaurecheck_cron_function( ) { global $post; $args = array( 'post_type' => 'place', 'posts_per_page' => -1, 'meta_query' => [[ 'key' => 'highlight', 'compare' => '<=', 'value' => time(), 'type' => 'NUMERIC' ]] ); $listings = get_posts( $args ); foreach($listings as $post) : update_post_meta($post->ID, 'highlight', '' ); endforeach; }

You’ll be in good company