If you’re using Cloudflare’s APO (Automatic Platform Optimization), you might want a quick way to purge individual pages from the cache.
(Similar to how WP Rocket lets you purge specific pages directly from the admin bar).
While Cloudflare’s WordPress plugin lets you purge the entire cache, sometimes you just need to clear a single page – like when you’re making small tweaks to your CSS.
In this tutorial, I’ll show you how to add a “Purge Current Page” button to your WordPress admin bar that lets you instantly clear the APO cache for the page you’re viewing.
The Code Snippet
You can either add this to your theme’s functions.php file, or use a code snippet manager like WPCodeBox (recommended).
<?php
/**
* Add Cloudflare APO Purge link to WordPress Admin bar
*/
function add_cloudflare_apo_purge_link() {
global $wp_admin_bar;
if (!is_admin_bar_showing() || !is_object($wp_admin_bar)) {
return;
}
// Check if we're on the front-end of the site
if (is_admin()) {
return;
}
$current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$wp_admin_bar->add_menu(array(
'id' => 'cloudflare-apo-purge',
'title' => 'Purge Current Page (Cloudflare APO)',
'href' => wp_nonce_url(admin_url('admin-ajax.php?action=purge_cloudflare_apo&url=' . urlencode($current_url)), 'purge_cloudflare_apo'),
'meta' => array(
'title' => 'Purge this page from Cloudflare APO cache',
'class' => 'cloudflare-apo-purge-link'
)
));
}
add_action('admin_bar_menu', 'add_cloudflare_apo_purge_link', 999);
/**
* Handle Cloudflare APO Purge action
*/
function handle_cloudflare_apo_purge() {
if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'purge_cloudflare_apo')) {
wp_die('Security check failed');
}
if (!current_user_can('manage_options')) {
wp_die('You do not have sufficient permissions to perform this action');
}
$url_to_purge = isset($_GET['url']) ? $_GET['url'] : '';
if (empty($url_to_purge)) {
wp_die('No URL specified for purging');
}
// Replace these with your actual Cloudflare details
$zone_id = 'YOURZONEID';
$api_token = 'YOURAPITOKEN';
$api_url = "https://api.cloudflare.com/client/v4/zones/{$zone_id}/purge_cache";
$response = wp_remote_post($api_url, array(
'headers' => array(
'Authorization' => 'Bearer ' . $api_token,
'Content-Type' => 'application/json'
),
'body' => json_encode(array(
'files' => array($url_to_purge)
))
));
if (is_wp_error($response)) {
wp_die('Error purging cache: ' . $response->get_error_message());
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
// Debug information
$debug_info = "Response Code: " . wp_remote_retrieve_response_code($response) . "\n";
$debug_info .= "Response Body: " . print_r($data, true);
if (isset($data['success']) && $data['success']) {
wp_redirect(add_query_arg('purge_success', '1', remove_query_arg(array('action', 'url', '_wpnonce'), wp_get_referer())));
exit;
} else {
wp_die('Error purging cache: ' . (isset($data['errors'][0]['message']) ? $data['errors'][0]['message'] : 'Unknown error') . "\n\nDebug Info:\n" . $debug_info);
}
}
add_action('wp_ajax_purge_cloudflare_apo', 'handle_cloudflare_apo_purge');
/**
* Display admin notice on successful purge
*/
function cloudflare_apo_purge_admin_notice() {
if (isset($_GET['purge_success'])) {
echo '<div class="notice notice-success is-dismissible"><p>Cloudflare APO cache purged successfully!</p></div>';
}
}
add_action('admin_notices', 'cloudflare_apo_purge_admin_notice');
Setting Up the Snippet
1. Get Your Cloudflare Details
Before the snippet will work, you’ll need two things from your Cloudflare account:
- Your Zone ID
- An API Token
To find your Zone ID, go to your domain’s overview page in Cloudflare. You’ll find it in the right sidebar under API > Zone ID.
For the API Token, go to your Cloudflare profile and create a new token with the following permissions:
- Zone > Cache Purge > Purge
- Zone > Zone > Read
2. Add Your Credentials
Replace these two lines with your actual Cloudflare details:
$zone_id = 'YOURZONEID';
$api_token = 'YOURAPITOKEN';
3. Test It Out
Once you’ve added the snippet and your credentials:
- Visit any page on your site’s front-end
- Look for the new “Purge Current Page (Cloudflare APO)” button in your admin bar
- Click it to purge that specific page from Cloudflare’s cache
You should see a success message if everything worked correctly.
How It Works
Let’s break down the main components of this snippet:
- The first function (
add_cloudflare_apo_purge_link
) adds the purge button to your admin bar, but only when viewing the front-end of your site. - When clicked, it sends an AJAX request to WordPress with the current page’s URL and a security nonce.
- The second function (
handle_cloudflare_apo_purge
) processes this request:- Verifies the security nonce
- Checks user permissions
- Sends a request to Cloudflare’s API to purge the specific URL
- Redirects back to the page with a success message
- The last function (
cloudflare_apo_purge_admin_notice
) displays the success message.
Security Considerations
The snippet includes several security measures:
- Only administrators can purge the cache
- WordPress nonces prevent CSRF attacks
- The API token should have minimal permissions (just cache purging)
However, I’m not a professional coder, so always make a backup of your site beforehand and use this snippet at your own risk.
Wrapping Up
You now have a convenient way to purge individual pages from Cloudflare’s APO cache right from your WordPress admin bar.
This can be especially useful during development or when making small tweaks to your site.
Let me know in the comments if you found this helpful!