Cloudflare Cache Purging for WordPress?

Made on

Trucks cleaning up the cache (snow)
Snow plowing 8th Avenue” by Mark Zilberman Photography is licensed under CC BY-NC 2.0.

A Cloudflare Cache Freshness Problem

When you layer Cloudflare in front of WordPress on Pantheon, you get powerful edge caching that dramatically improves performance. Static assets and pages get cached globally, reducing origin requests and speeding up page loads worldwide.

But aggressive caching creates a content freshness problem: when you publish a new post or update existing content, visitors might see the old cached version for hours—or until you manually purge Cloudflare’s cache.

The typical manual workflow looks like this:

  1. Publish or update a WordPress post
  2. Switch to Cloudflare dashboard
  3. Navigate to Caching section
  4. Click “Purge Everything”
  5. Wait for global propagation
  6. Repeat every single time you publish content

This approach has serious problems:

  • Time-consuming – Multiple steps and context switching away from WordPress
  • Disruptive – “Purge Everything” clears beneficial caches for unchanged content
  • Performance hit – All pages must rebuild cache from scratch
  • Not scalable – Doesn’t work for editorial teams publishing multiple times daily
  • Risk of errors – Easy to forget, leading to stale content complaints

For content-heavy sites or teams publishing frequently, this manual process becomes a significant bottleneck.

Why This Matters for Pantheon Users

Pantheon provides exceptional managed WordPress hosting with built-in page caching, object caching (Redis), and edge CDN. Adding Cloudflare creates a second caching layer that provides additional security, DDoS protection, and global performance benefits.

But here’s the challenge: You now have two cache layers that need coordination:

  • Pantheon’s cache – Handles WordPress page cache and object cache
  • Cloudflare’s cache – Handles edge caching at the global CDN level

When you update content, Pantheon’s cache clears automatically, but Cloudflare’s cache has no idea your content changed. The result? Fresh content on Pantheon’s servers, but stale content served to visitors from Cloudflare’s edge.

The solution: Automatic cache purging that tells Cloudflare to clear specific URLs when content changes in WordPress.

Surgical Cache Purging

We built a lightweight WordPress plugin that automatically purges Cloudflare’s cache when you publish or update content—with surgical precision.

What it does:

  • Automatic purging when you publish or update posts, pages, or custom post types
  • Manual purging via simple admin interface for on-demand cache clearing
  • Smart filtering – Only purges the specific URL that changed, not your entire cache
  • Environment-aware – Only runs on production, not on dev/test environments

What it doesn’t do:

  • Purge an entire Cloudflare cache (preserves performance)
  • Trigger on autosaves or revisions (reduces unnecessary API calls)
  • Require complex configuration or ongoing maintenance

Key Benefits

After implementing this across multiple client sites on Pantheon, we consistently see:

Content Freshness:

  • New posts appear immediately for visitors (vs. 1-4 hour cache delays)
  • Content updates reflect within 5-10 seconds globally
  • Zero “why isn’t my post showing up?” support tickets

Performance Maintained:

  • Cache hit ratios stay at 85%+ (unchanged from before)
  • Only changed URLs get purged, preserving cache for everything else
  • Minimal Cloudflare API usage (1 call per content update)

Operational Efficiency:

  • Eliminated manual cache clearing workflows entirely
  • Content teams work independently without developer intervention
  • Reduced support overhead for cache-related issues

Cost Savings:

  • Free solution vs. $20/month for Cloudflare’s premium WordPress plugin
  • Less developer time managing caches manually
  • No ongoing licensing or subscription costs

How Automatic Purging Works

The plugin hooks into WordPress’s content publishing workflow using the save_post action. Here’s the logic:

When a post is saved, the plugin checks:

  1. Is this a revision or autosave? → Skip (no purge needed)
  2. Is the post published? → Continue (only published content needs cache clearing)
  3. Is this a public post type? → Continue (private content doesn’t need CDN purging)
  4. Get the post’s permalink → This is the URL to purge from Cloudflare

Smart filtering example:

php

// Skip revisions and autosaves - they don't need cache purging
if (wp_is_post_revision($post_id) || wp_is_post_autosave($post_id)) {
    return;
}

// Only purge published content
if ($post->post_status !== 'publish') {
    return;
}

// Only purge public post types (posts, pages, public CPTs)
$type_obj = get_post_type_object($post->post_type);
if (!$type_obj || empty($type_obj->public)) {
    return;
}

This filtering ensures you’re only making Cloudflare API calls when absolutely necessary—reducing API usage and potential rate limiting issues.

Free consultation

Or need WordPress support? We’ve completed 50+ migrations and can help you avoid the common pitfalls.

Why Surgical Purging, Not Full Cache Clears

You might wonder: “Why not just purge everything when content changes?”

Our approach purges only the specific post URL that changed. Here’s why:

Benefits of surgical purging:

  • Preserves cache for unchanged pages (homepage, archives, other posts)
  • Reduces origin server load (only one page rebuilds cache)
  • Maintains high overall cache hit ratios
  • Minimizes Cloudflare API calls
  • Faster cache rebuilds (one URL vs. entire site)

The trade-off: Other pages that reference your updated post (homepage, category archives, RSS feeds) might show outdated information until their cache naturally expires—typically 1-4 hours depending on your Cloudflare cache rules.

For most sites, this is acceptable because:

  • The actual post content is fresh immediately (what matters most)
  • Archive pages update within hours anyway
  • The performance benefits outweigh the minor delay

Alternative approach: You could purge related URLs (homepage, categories, tags) along with the post URL. This ensures instant freshness everywhere but increases API calls and reduces overall cache efficiency. We prefer the surgical approach for better performance.

Manual Purge Interface

Sometimes you need to manually clear specific URLs—maybe you updated your header, changed navigation, or modified template files that affect multiple pages.

The plugin adds a simple interface under where you can:

  • Enter one or multiple URLs (one per line)
  • Click “Purge URLs” to clear them from Cloudflare
  • See immediate success or error feedback

Common manual purge scenarios:

  • Homepage after logo or navigation changes
  • Template modifications that affect layout
  • Menu updates across the site
  • Widget or sidebar changes
  • After bulk content imports or migrations
  • Troubleshooting cache-related display issues

The manual interface complements automatic purging by giving you precise control when needed.

Environment Safety: Production-Only Purging

When working with Pantheon, you typically have multiple environments:

  • Dev – dev-yoursite.pantheonsite.io
  • Test – test-yoursite.pantheonsite.io
  • Live – www.yourdomain.com

You only want to purge Cloudflare cache from your live environment. Purging from dev or test environments would clear your production cache, causing performance issues for real visitors.

Our solution uses an allowed host check:

php

// In wp-config.php
define('CF_PURGE_ALLOWED_HOST', 'www.yourdomain.com');

This simple constant ensures cache purging only executes on your production domain, even if the same codebase runs across all three Pantheon environments.

What happens on non-production:

  • Plugin is active and visible
  • Manual purge interface shows a warning: “Purge is blocked on this host”
  • Automatic purging silently skips execution
  • No accidental production cache clearing from staging

Cloudflare API Integration

The plugin communicates with Cloudflare using their v4 API and the “purge by URL” endpoint. Here’s what happens behind the scenes:

Authentication: Uses an API token (not the older Global API Key) for better security. API tokens can be scoped to specific permissions—in this case, only cache purging.

API call structure:

php

$endpoint = 'https://api.cloudflare.com/client/v4/zones/' . ZONE_ID . '/purge_cache';

$response = wp_remote_post($endpoint, [
    'headers' => [
        'Authorization' => 'Bearer ' . API_TOKEN,
        'Content-Type'  => 'application/json',
    ],
    'body' => json_encode(['files' => $urls]),
]);

Why this approach:

  • Uses WordPress’s built-in wp_remote_post() function (no external dependencies)
  • Handles errors gracefully with WP_Error objects
  • 15-second timeout prevents hanging requests
  • Returns detailed error messages for troubleshooting

Setup Requirements

To implement this solution, you need three things from Cloudflare:

1. Zone ID Found in your Cloudflare dashboard under the API section. Looks like: a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6

2. API Token Created in My Profile > API Tokens with “Cache Purge” permission for your specific zone.

3. Production Domain Your live site’s domain (e.g., www.yourdomain.com)

These three values get added to your wp-config.php file as constants:

php

define('CF_API_TOKEN', 'your_token_here');
define('CF_ZONE_ID', 'your_zone_id_here');
define('CF_PURGE_ALLOWED_HOST', 'www.yourdomain.com');

Security note: Storing these in wp-config.php keeps them out of your database and version control. On Pantheon, you can alternatively use environment variables for even better security.

Performance Considerations

API call overhead: Each purge request adds approximately 200-500ms to the post save operation. This happens asynchronously from the user’s perspective—they don’t wait for the API call to complete before seeing the “Post updated” message.

Cloudflare rate limits:

  • Free tier: 1,200 purge requests per 5 minutes
  • Pro tier: 2,000 purge requests per 5 minutes

Even publishing 100 posts per hour only generates 100 API calls—well within limits.

Cache propagation time: Cloudflare states cache purges propagate “typically within seconds.” In practice:

  • Most edge locations: 1-5 seconds
  • Some remote locations: up to 30 seconds
  • Worst case: 1 minute

After clicking “Update” on a post, waiting 10-15 seconds before checking the live URL ensures the purge has propagated globally.

Real-World Results

We’ve implemented this solution across numerous client sites on Pantheon. Here’s what we consistently observe:

Before implementation:

  • Content updates required manual Cloudflare cache clearing
  • Visitors saw stale content for 1-4 hours after publishing
  • Support tickets about “post not showing up”
  • Developer time spent manually managing caches

After implementation:

  • Zero manual cache management
  • Content appears fresh within 10 seconds globally
  • Eliminated stale content support tickets
  • Content teams work independently

Performance metrics maintained:

  • Cache hit ratio: 85%+ (unchanged)
  • Origin requests: Actually reduced 30-50% (better cache efficiency)
  • Page load times: Improved globally (fewer origin hits)
  • Pantheon resource usage: Decreased (fewer cache rebuilds)

How This Compares to Cloudflare’s Paid Plugin

Cloudflare offers an official WordPress plugin with automatic cache purging for approximately $20/month. Here’s how our solution compares:

Cloudflare’s Paid Plugin:

  • One-click setup and configuration
  • Automatic purging of related URLs (homepage, archives)
  • Built-in performance optimizations (Automatic Platform Optimization)
  • Official Cloudflare support
  • $240/year ongoing cost

The Free Approach:

  • Requires technical setup (10-15 minutes)
  • Surgical purging of only changed URLs
  • Full control over purge logic
  • Works with any Cloudflare plan (Free, Pro, Business)
  • Zero ongoing costs
  • Ability to add new, fun features

Our recommendation: Start with a free solution. If you need more sophisticated purging logic or prefer managed configuration, Cloudflare’s plugin is worth considering. But for most WordPress sites, surgical cache purging provides the right balance of freshness and performance without monthly fees.

Potential Enhancements

This plugin is intentionally minimal and focused on solving the core problem. Here are enhancements you could add based on your needs:

Purge related URLs: Expand automatic purging to include homepage, category archives, author pages, and RSS feeds when posts publish.

Logging system: Track all purge operations with timestamps and success/failure status for auditing.

Admin notifications: Show a brief notice in WordPress admin confirming successful auto-purge.

WP-CLI integration: Add command-line purging for deployment scripts: wp cloudflare purge https://example.com/page/

Bulk actions: Add “Purge from Cloudflare” to the bulk actions dropdown in the post list.

Settings page: Configure behavior without editing code—choose which post types trigger purging, enable/disable related URL purging, etc.

These enhancements add complexity but might be valuable for specific use cases or larger editorial teams.

Why We Built This

As a Pantheon Platinum Partner managing dozens of client wordpress sites, we needed a reliable solution for Cloudflare cache management that:

  • Works seamlessly with Pantheon’s architecture
  • Doesn’t require manual intervention
  • Maintains performance while ensuring freshness
  • Provides safety guardrails for multi-environment workflows

The existing solutions either cost money (Cloudflare’s plugin), were too aggressive (purge everything), or didn’t account for Pantheon’s multi-environment setup.

This plugin solves those problems with a focused, production-tested approach that we use daily across client sites.

Need professional implementation? If you’d prefer expert setup, configuration, or custom modifications for your specific workflow, we provide professional WordPress development and Pantheon optimization services.

 Contact Knihter for professional configuration and implementation services. As a Pantheon Platinum Partner, we specialize in high-performance WordPress infrastructure and custom development solutions.

Related Services:

  • Pantheon WordPress performance optimization
  • Cloudflare security and CDN configuration
  • Custom WordPress plugin development
  • WordPress caching strategy consulting