Clear Bunny.net CDN Cache in WordPress When WP Rocket Cache is Cleared
The Bunny.net WordPress plugin is... not great. It has a 3.1/5 stars on WordPress and it rewrote all of my CDN URLs automatically to the wrong URL. So I sought out to build something simpler that just clears my CDN cache when I purge WP Rocket's cache.
Simply drop this in your theme's functions.php file. Remember to swap out your API key and zone ID. Once installed, just clear your WP Rocket cache as normal and your CDN Cache will be cleared too!
/*
* Clear Bunny.net CDN cache when WP Rocket cache is cleared
*/
function cp_purge_bunny_cdn_cache() {
$bunny_api_key = 'api_key_here';
$pull_zone_id = 'pull_zone_id_here';
// Purge entire Pull Zone cache
$purge_url = 'https://api.bunny.net/pullzone/' . $pull_zone_id . '/purgeCache';
$response = wp_remote_post($purge_url, array(
'headers' => array(
'AccessKey' => $bunny_api_key,
'Content-Type' => 'application/json'
),
'timeout' => 30
));
if (is_wp_error($response)) {
error_log('Bunny.net cache purge failed: ' . $response->get_error_message());
return false;
}
$status_code = wp_remote_retrieve_response_code($response);
if ($status_code >= 200 && $status_code < 300) {
error_log('Bunny.net cache purge successful (status: ' . $status_code . ')');
return true;
} else {
$body = wp_remote_retrieve_body($response);
error_log('Bunny.net cache purge failed - status: ' . $status_code . ' body: ' . $body);
return false;
}
}
// Hook into WP Rocket cache clearing events
add_action('rocket_purge_cache', 'cp_purge_bunny_cdn_cache');
add_action('after_rocket_clean_domain', 'cp_purge_bunny_cdn_cache');
add_action('after_rocket_clean_post', 'cp_purge_bunny_cdn_cache');
add_action('after_rocket_clean_files', 'cp_purge_bunny_cdn_cache');
add_action('after_rocket_clean_home', 'cp_purge_bunny_cdn_cache');
add_action('rocket_rucss_complete_job_status', 'cp_purge_bunny_cdn_cache');
Comments