Skip to content

Instantly share code, notes, and snippets.

@esaesa
Forked from rmens/cf-purge-wp.php
Created December 22, 2024 17:55
Show Gist options
  • Save esaesa/a34ba1e65978fdc869afd657e3a7e177 to your computer and use it in GitHub Desktop.
Save esaesa/a34ba1e65978fdc869afd657e3a7e177 to your computer and use it in GitHub Desktop.
Cloudflare cache purge WP
<?php
/**
* Plugin Name: Cloudflare Cache Purge Extended
* Description: Purges Cloudflare cache for the front page, specific post, wp-json routes, and general posts endpoint when a post is published, updated, scheduled, or trashed.
* Version: 1.1
* Author: Raymon Mens
*/
// Cloudflare settings
$cloudflare_zone_id = 'YOUR_ZONE_ID';
$cloudflare_api_token = 'YOUR_API_TOKEN';
$cloudflare_purge_debug = 0; // Set to 1 to enable debugging
function purge_cloudflare_cache($post_id, $post = null) {
global $cloudflare_zone_id, $cloudflare_api_token, $cloudflare_purge_debug;
if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
return;
}
$home_url = home_url('/');
$post_url = get_permalink($post_id);
$json_url = home_url("/wp-json/wp/v2/posts/{$post_id}");
$json_all_posts_url = home_url("/wp-json/wp/v2/posts");
$url = 'https://api.cloudflare.com/client/v4/zones/' . $cloudflare_zone_id . '/purge_cache';
$data = [
'files' => [$home_url, $post_url, $json_url, $json_all_posts_url]
];
$headers = [
'Authorization' => 'Bearer ' . $cloudflare_api_token,
'Content-Type' => 'application/json'
];
$response = wp_remote_post($url, [
'headers' => $headers,
'body' => json_encode($data),
'method' => 'POST',
'data_format' => 'body'
]);
// Response handling
if (is_wp_error($response)) {
if ($cloudflare_purge_debug) {
error_log('Error purging Cloudflare cache: ' . $response->get_error_message());
}
return;
}
$response_code = wp_remote_retrieve_response_code($response);
$response_body = wp_remote_retrieve_body($response);
$response_data = json_decode($response_body, true);
if ($response_code == 200) {
if ($cloudflare_purge_debug) {
error_log('Cloudflare cache purged successfully: ' . print_r($response_data, true));
}
} else {
if ($cloudflare_purge_debug) {
error_log('Cloudflare API returned an error: ' . print_r($response_data, true));
}
}
}
// Hook into actions for publishing, updating, scheduling, and trashing posts
add_action('publish_post', 'purge_cloudflare_cache', 10, 2);
add_action('post_updated', 'purge_cloudflare_cache', 10, 2);
add_action('publish_future_post', 'purge_cloudflare_cache', 10, 1);
add_action('trashed_post', 'purge_cloudflare_cache', 10, 2);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment