Reputation: 11
I've implemented a custom functionality in WordPress to automatically set alert banners (custom_alert
post type) to 'draft' status upon expiration, using a custom field alert_expiration_date
. When an alert expires, I only want to purge the cache for the pages associated with that alert (defined in the alert_pages
custom field), not the entire site. Here's the relevant part of my code:
add_filter('cron_schedules', 'add_custom_cron_schedule');
function add_custom_cron_schedule($schedules) {
if (!isset($schedules["every_two_minutes"])) {
$schedules['every_two_minutes'] = array(
'interval' => 120, // 2 minutes en secondes
'display' => esc_html__('Every Two Minutes')
);
}
return $schedules;
}
if (!wp_next_scheduled('expire_alerts_check')) {
wp_schedule_event(time(), 'every_two_minutes', 'expire_alerts_check');
}
add_action('expire_alerts_check', 'expire_and_purge_function');
function expire_and_purge_function() {
$today = date('Y-m-d H:i:s', current_time('timestamp', 0));
$args = [
'post_type' => 'custom_alert',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => [
[
'key' => 'alert_expiration_date',
'value' => $today,
'compare' => '<=',
'type' => 'DATETIME'
]
]
];
$posts = get_posts($args);
foreach ($posts as $post) {
$expiration_date = get_field('alert_expiration_date', $post->ID);
if ($expiration_date && strtotime($expiration_date) <= strtotime($today)) {
wp_update_post([
'ID' => $post->ID,
'post_status' => 'draft'
]);
$pages_to_update = get_field('alert_pages', $post->ID);
if (!empty($pages_to_update)) {
purge_pages_cache($pages_to_update);
}
}
}
}
function purge_pages_cache($pages_to_update) {
foreach ($pages_to_update as $page_id) {
do_action('litespeed_purge_post', $page_id);
log_purge_action($page_id);
}
}
However, I'm encountering an issue where the cache for all pages on the site seems to be purged instead of just the specific pages associated with the expired alert.
Upvotes: 1
Views: 115