I have a custom post type ("fecha") that contains past events (birthdates of famous people, historical dates, etc). Within these posts, a custom field ("aniversario") calculates how many years have passed since the original date.
This value is stored when the post is created and saved, so I need to update these custom posts (all of them) every year so that this custom field keeps being valid. I am trying to use cron (with a daily schedule) to call an update_post_meta, without success. All posts in these custom post type are private and appear only in the admin side.
The website is personal and for non-comercial pourposes (I´m a freelance science writer, this is an attempt to build a personal editorial calendar, wich would help me enormously).
Any help pointing errors in code or something missing, would be great. The code is as follows (it is located in my functions.php):
function run_update_fecha_cron_job() {
$posts = get_posts([
'post_type' => 'fecha',
'post_status' => 'any',
'posts_per_page' => -1, // getting all posts of a post type
'no_found_rows' => true, // speeds up a query significantly and can be set to 'true' if we don't use pagination
'fields' => 'ids' // again, for performance
]);
// now check meta and update custom fields for every post
foreach ($posts as $post_id) {
/*
* calculate how many years have passed by sustracting the value from
* another custom field called "wpcf-ano" to current year, then store calculated value in
* variable "$aniversario", wich should be "1" if nothing is stored in "wpcf-ano"
*/
$ano = get_post_meta($post_id, 'wpcf-ano', TRUE);
if (!empty($ano)) {
$year_diff = date("Y") - $ano;
$aniversario = $year_diff;
} else {
$aniversario = 1;
}
// update custom field
update_post_meta($post_id, 'aniversario', $aniversario);
}
}
// Schedule Cron Job Event
function update_fecha_cron_job() {
if (!wp_next_scheduled('run_update_fecha_cron_job')) {
wp_schedule_event(current_time('timestamp'), 'daily', 'run_update_fecha_cron_job');
}
}
add_action('wp', 'update_fecha_cron_job');
add_action('run_update_fecha_cron_job', 'run_update_fecha_cron_job');