I'm using a Custom Post Type to show events on my site. The events have two custom fields for the start and the end date. The dates are stored in the following format: YYYY-MM-DD.
I'm using the field to sort the events in the frontend where I start with the next event based on the current date.
After this date, the events are not showing in the frontend anymore because they lie in the past.
Now I want to delete the events after the end date. Is there any way to do this?
I've found a nice solution from @pieter-goosen to delete posts after a number of days: https://wordpress.stackexchange.com/questions/209046/delete-expired-posts-after-a-number-of-days-after-they-expired
But I don't know how to use this function with a meta field.
Any ideas/hints?
My code:
function expirePastEvents() {
$current_date_query = date ('Y-m-d');
$postType = 'event'; // Change this to your post type name.
$metaKeyName = 'gid_22'; // Change this to your meta key name for end date.
$skipTrash = false; // Whether or not to skip the trash.
$posts = new WP_Query([
'post_type' => $postType,
'fields' => 'ids',
'post_status' => 'publish',
'meta_query' => [
[
'key' => $metaKeyName,
//'value' => current_time('timestamp'),
'value' => $current_date_query,
'compare' => '<='
]
]
]);
foreach ($posts->posts as $post) {
wp_delete_post($post->ID, $skipTrash);
}
}
// expired_post_delete hook fires when the Cron is executed
add_action( 'expired_post_delete', 'expirePastEvents' );
// Add function to register event to wp
add_action( 'wp', 'register_daily_events_delete_event');
function register_daily_events_delete_event() {
// Make sure this event hasn't been scheduled
if( !wp_next_scheduled( 'expired_post_delete' ) ) {
// Schedule the event
wp_schedule_event( time(), 'hourly', 'expired_post_delete' );
}
}