Tell us what you are trying to do?
I have a Taxonomy named Grant status -> open, closed
I have a custom field Final closing date ex value: June 10,2024 .
I want to auto update the taxonomy open or closed based on final closing date.
I referred the save_post documentation and used this code to update the taxonomy based on comparision and made this function as cron event to run daily.
Below is the code i tried but the taxonomy is not updating correctly it showing grant closed for all the posts.
function update_grant_status_auto() {
// Get all posts with the custom field final-closing-date
$args = array(
'post_type' => 'posts', // Replace with your custom post type
'meta_query' => array(
array(
'key' => 'wpcf-final-closing-date',
'compare' => 'EXISTS'
),
),
'posts_per_page' => -1 // Retrieve all posts
);
$query = new WP_Query($args);
// $today = current_time('Y-m-d'); // Get today's date in 'Y-m-d' format
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$post_id = get_the_ID();
$final_closing_date = get_post_meta($post_id, 'wpcf-final-closing-date', true);
if(empty($final_closing_date) || $final_closing_date > time() )
{
wp_set_object_terms($post_id, 'grant-open', 'grant-status-auto');
} else if ($final_closing_date < time()) {
wp_set_object_terms($post_id, 'grant-closed', 'grant-status-auto');
}
}
wp_reset_postdata();
}
}
// Hook the function to a WordPress action, such as 'init' or a scheduled event
add_action('init', 'update_grant_status_auto');
// Optional: Schedule the function to run daily using WP Cron
if (!wp_next_scheduled('update_grant_status_daily_auto')) {
wp_schedule_event(time(), 'daily', 'update_grant_status_daily_auto');
}
add_action('update_grant_status_daily_auto', 'update_grant_status_auto');
Please guide me how to auto update the taxonomy terms based on custom field date value.