Last active
July 21, 2023 14:45
-
-
Save DamChtlv/dafde45c2339b6b2cc2d649bb2aee66b to your computer and use it in GitHub Desktop.
Force clear Cloudflare cache after WP Rocket has cleared his own cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// WPRocket hook | |
add_action( 'after_rocket_clean_domain', 'force_purge_cloudflare' ); | |
// Clear cache of Cloudflare after WPRocket cleared his cache | |
function force_purge_cloudflare() { | |
$rocket_settings = get_option( 'wp_rocket_settings' ) ?: array(); | |
if ( !$rocket_settings ) { | |
return; | |
} | |
$zone_id = !empty( $rocket_settings['cloudflare_zone_id'] ) ? sanitize_text_field( $rocket_settings['cloudflare_zone_id'] ) : ''; | |
$api_key = !empty( $rocket_settings['cloudflare_api_key'] ) ? sanitize_text_field( $rocket_settings['cloudflare_api_key'] ) : ''; | |
$email = !empty( $rocket_settings['cloudflare_email'] ) ? sanitize_email( $rocket_settings['cloudflare_email'] ) : ''; | |
try { | |
$headers = array( | |
'Content-Type' => 'application/json', | |
'X-Auth-Email' => $email, | |
'X-Auth-Key' => $api_key, | |
'cache-control' => 'no-cache', | |
'User-Agent' => 'wp-rocket/' . rocket_get_constant( 'WP_ROCKET_VERSION' ), | |
); | |
$response = wp_remote_request( | |
"https://api.cloudflare.com/client/v4/zones/$zone_id/purge_cache", | |
array( | |
'method' => 'DELETE', | |
'headers' => $headers, | |
'body' => wp_json_encode( array( 'purge_everything' => true ) ), | |
) | |
); | |
if ( is_wp_error( $response ) ) { | |
return; | |
} | |
$content = wp_remote_retrieve_body( $response ); | |
if ( !$content ) { | |
return; | |
} | |
$content = json_decode( $content ); | |
if ( empty( $content->success ) ) { | |
return; | |
} | |
// Cloudflare cache cleared | |
} catch ( Exception $e ) { | |
print_r( $e ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment