Custom Purge (Automatic on Wordpress)

You need to add this code to the functions.php file in your theme.

What is it useful for?
This code ensures that only the homepage and post cache in the cloudflare cache is deleted when you publish a new post or change an existing post. Thus, updated content is presented to users instantly. This way, the entire cache is not deleted and there is no performance loss.

Dont forget change your api key , zone ID and e mail.

CODE :

function cloudflare_purge_cache_on_publish($post_id) {
    $post = get_post($post_id);
    $url = get_permalink($post);
    $homepage_url = home_url('/');

    $api_key = 'Your API KEY';
    $email = 'Your Cloudflare e-mail';
    $zone_id = 'your Zone ID';

    $urls = array($url, $homepage_url);

    $data = json_encode(array("files" => $urls));

    $response = wp_remote_post("https://api.cloudflare.com/client/v4/zones/$zone_id/purge_cache", array(
        'method' => 'POST',
        'headers' => array(
            'Content-Type' => 'application/json',
            'X-Auth-Email' => $email,
            'X-Auth-Key' => $api_key,
        ),
        'body' => $data,
    ));

    if (is_wp_error($response)) {
        error_log('Cloudflare cache purge failed: ' . $response->get_error_message());
    } else {
        $body = wp_remote_retrieve_body($response);
        $result = json_decode($body);
        if (!$result->success) {
            error_log('Cloudflare cache purge failed: ' . json_encode($result->errors));
        }
    }
}
add_action('save_post', 'cloudflare_purge_cache_on_publish');

Note : For security reasons, you can may call your API and zone keys from another config file.

1 Like

Pretty cool! It’s somewhat the missing link for users who don’t want to use APO, but have their cache rules set up similar to how APO does it.

My only recommendation would be to use an API token for purges, as it’s more secure should it be compromised.

1 Like

I turned this into a Plugin:

<?php

/*
Plugin Name: Purger for WordPress
Description: Purge home page and post when saving
Version: 1.0
Author: Cloudflare Community @h.serpin033 & @sdayman
Requires: CLOUDFLARE_ZONE_ID CLOUDFLARE_API_TOKEN defined in wp-config.php
*/

/* Start Adding Functions Below this Line */

add_action('save_post', 'cloudflare_purge_cache_on_publish');

function cloudflare_purge_cache_on_publish($post_id) {
    $post = get_post($post_id);
    if ($post->post_status != 'publish') {
        return; // Only purge cache if the post is published
    }

    $url = get_permalink($post);
    $homepage_url = home_url('/');

    // Replace these with environment variables or WP options
    $api_token = CLOUDFLARE_API_TOKEN;
    $zone_id = CLOUDFLARE_ZONE_ID;

    if (!$api_token || !$zone_id) {
        error_log('Cloudflare API credentials are not set.');
        return;
    }

    $urls = array($url, $homepage_url);

    $data = json_encode(array("files" => $urls));

    $response = wp_remote_post("https://api.cloudflare.com/client/v4/zones/$zone_id/purge_cache", array(
        'method' => 'POST',
        'headers' => array(
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . $api_token,
        ),
        'body' => $data,
    ));

    if (is_wp_error($response)) {
        error_log('Cloudflare cache purge failed: ' . $response->get_error_message());
    } else {
        $body = wp_remote_retrieve_body($response);
        $result = json_decode($body);
        if (!$result->success) {
            error_log('Cloudflare cache purge failed: ' . json_encode($result->errors));
        } else {
            error_log('Cloudflare cache purged successfully.');
        }
    }
}

/* Stop Adding Functions Below this Line */

?>
1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.