Skip to content

Instantly share code, notes, and snippets.

@tomasbasham
Created November 3, 2021 16:21
Show Gist options
  • Save tomasbasham/8c00929f93b1f2bba197849b1ebb916c to your computer and use it in GitHub Desktop.
Save tomasbasham/8c00929f93b1f2bba197849b1ebb916c to your computer and use it in GitHub Desktop.
Control Cloudflare Edge Caching
/*
* Add a specific Cloudflare edge cache HTTP header to each HTTP response
* preventing defined pages from being cached at the edge. This is done
* selectively since some pages require dynamic content based on external
* factors such as geographic location of the request. All other static
* content will continue to be cached (i.e. JavaScript, CSS, images).
*
* To control the caching behaviour at the edge add a custom metadata field
* to the page:
*
* field name : cache_option
* field value : no-cache|location-cache
*
*/
add_filter('wp_headers', 'edge_cache');
function edge_cache($headers) {
// Using get_the_ID() is not possible within this hook because the global
// $post variable will not have been set by the Wordpress run loop. This
// code recreates the current request URL and uses a global Wordpress function
// to fetch the post ID.
$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$current_post_id = url_to_postid( $url );
switch (get_metadata('post', $current_post_id, 'cache_option', true)) {
case 'no-cache':
$headers['cf-edge-cache'] = 'no-cache';
break;
case 'location-cache':
$headers['Vary'] = 'Cf-Ipcountry';
break;
}
return $headers;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment