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.

Revisions

  1. tomasbasham revised this gist Nov 3, 2021. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions edge_cache.php
    Original file line number Diff line number Diff line change
    @@ -12,8 +12,8 @@
    * field value : no-cache|location-cache
    *
    */
    add_filter('wp_headers', 'no_edge_cache');
    function no_edge_cache($headers) {
    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
  2. tomasbasham created this gist Nov 3, 2021.
    34 changes: 34 additions & 0 deletions edge_cache.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    /*
    * 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', 'no_edge_cache');
    function no_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;
    }