thanks very much for your reply.
i have followed your instructions about the setup and have not changed any settings on the cloudflare side, so only one page rule written automatically by your plugin.
no error logs and no access log either. I tried a few approaches and somehow the cached pages did not update (eg. incogonito mode chrome kept loading cached page).
but this solution seems to work > I flush the cache at Cloudflare level and add purge flash hook on post save.
so now when i have a page open in chrome and reload it, the cf-cache-status: is MISS and on another page load it`s HIT, and AGE gets reset.
function purge_cloudflare_cache_on_post_save( $post_id ) {
// Avoid triggering during autosave or if not a valid post type
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Cloudflare Zone ID and API Token
$zone_id = 'xxxxxxx';
$api_token = 'xxxxxxx';
// Build the API endpoint
$url = "https://api.cloudflare.com/client/v4/zones/{$zone_id}/purge_cache";
// Body for the API request (purge all cache)
$body = json_encode( array( 'purge_everything' => true ) );
// Set up request headers
$headers = array(
'Content-Type' => 'application/json',
'Authorization' => "Bearer {$api_token}",
);
// Send the request to Cloudflare API
$response = wp_remote_post( $url, array(
'method' => 'POST',
'body' => $body,
'headers' => $headers,
) );
// Optional: Log the response for debugging
if ( is_wp_error( $response ) ) {
error_log( 'Cloudflare Cache Purge Failed: ' . $response->get_error_message() );
} else {
$response_body = wp_remote_retrieve_body( $response );
error_log( 'Cloudflare Cache Purge Response: ' . $response_body );
}
}
add_action( 'save_post', 'purge_cloudflare_cache_on_post_save' );
function purge_cache_on_save_or_update( $post_id, $post, $update ) {
// Prevent autosave from triggering cache purge
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Purge the cache
do_action( "swcfpc_purge_cache" );
// Log cache purge success in the access log
if ( did_action( "swcfpc_purge_cache" ) ) {
error_log( "Cache purged for post ID: " . $post_id . " on " . date( 'Y-m-d H:i:s' ) );
} else {
error_log( "Cache purge failed for post ID: " . $post_id . " on " . date( 'Y-m-d H:i:s' ) );
}
// Add a transient to show an admin notice
set_transient( 'cache_purge_notice', true, 10 );
}
add_action( 'save_post', 'purge_cache_on_save_or_update', 10, 3 );
function display_cache_purge_notice() {
if ( get_transient( 'cache_purge_notice' ) ) {
echo '<div class="notice notice-success is-dismissible"><p>Cache purged successfully!</p></div>';
delete_transient( 'cache_purge_notice' );
}
}
add_action( 'admin_notices', 'display_cache_purge_notice' );
-
This reply was modified 2 months, 2 weeks ago by
dariobros.