/* * 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; }