WordPress 发布更新文章后自动清理 CloudFlare 缓存

源码介绍

下面的代码是需要提供当前站点 CloudFlare 账户的 Global API Key、账号邮箱地址、以及对应网站区域 ID(Zone_ID)的。

Global API Key:可以在 CloudFlare 后台【概述】点击右边底部【获取您的 API 令牌】在【API 密钥】里查看到的。

账号邮箱:就是你注册 CloudFlare 账号时的邮箱地址。

区域 ID:就是 CloudFlare 后台站点【概述】右边显示的区域 ID 也叫 Zone ID。

源码内容

/*当有新文章发布或者编辑更新文章的时候自动清理 CloudFlare 首页和对应文章链接缓存。*/
function mydl_clear_cloudflare_cache($post_id) {
    // 获取文章的 URL
    $post_url = get_permalink($post_id);
    // 获取首页的 URL
    $home_url = home_url('/');
    // CloudFlare API 信息
    $api_key = 'your_Global API Key';
    $email = 'your_email';
    $zone_id = 'your_zone_id';
    // 要清理的 URL 列表
    $urls = array($post_url, $home_url);
    // 清理缓存的 API 请求
    $response = wp_remote_post("https://api.cloudflare.com/client/v4/zones/{$zone_id}/purge_cache", array(
        'method' => 'POST',
        'headers' => array(
            'X-Auth-Email' => $email,
            'X-Auth-Key' => $api_key,
            'Content-Type' => 'application/json',
        ),
        'body' => json_encode(array(
            'files' => $urls,
        )),
    ));
    // 检查 API 响应
    if (is_wp_error($response)) {
        error_log('CloudFlare 缓存清理无效: ' . $response->get_error_message());
    } else {
        error_log('已经清理了 CloudFlare 缓存链接: ' . implode(', ', $urls));
    }
}
// 钩子函数,在文章发布或更新时调用
add_action('save_post', 'mydl_clear_cloudflare_cache');
有问题及时联系站长,QQ:1240555208
更多优质资源在QQ群里,可以进群领取:467392290~
© 版权声明
THE END
点赞9 分享
及时反馈~ 抢沙发

请登录后发表评论

    暂无评论内容