Last active
April 18, 2026 11:11
-
-
Save dannyvankooten/4776587a7d39e04fab54305bcb7a7642 to your computer and use it in GitHub Desktop.
WordPress plugin to set HTTP Cache-Control headers on all cache-able requests. Use this in combination with caching at the edge (Bunny CDN, Cloudflare, ...) to make your site fly. Use with caution if your site has dynamic content.
This file contains hidden or 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 | |
| /* | |
| Plugin Name: Cache Headers | |
| Description: Sets Cache-Control headers on all GET requests for logged-out visitors | |
| Author: Danny van Kooten | |
| Author URI: https://dannyvankooten.com/ | |
| Private: True | |
| */ | |
| add_filter('wp_headers', function ($headers) { | |
| // do not set cache headers in debug mode | |
| if (isset($headers['Cache-Control']) || is_admin() || WP_DEBUG) { | |
| return $headers; | |
| } | |
| // only set cache-headers on safe HTTP methods | |
| $method = $_SERVER['REQUEST_METHOD'] ?? 'POST'; | |
| if ($method !== 'GET') { | |
| return $headers; | |
| } | |
| // never set cache headers for logged-in users | |
| if (is_user_logged_in()) { | |
| $headers["Cache-Control"] = "must-revalidate, max-age=0, private"; | |
| // cache 404 pages for 1 hour | |
| } elseif (is_404()) { | |
| $headers["Cache-Control"] = "public, max-age=3600"; | |
| // cache all other pages for 30 days | |
| } else { | |
| $headers["Cache-Control"] = "public, max-age=2592000"; | |
| } | |
| return $headers; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You may also consider dropping cache haeders on the following:
Path Exclusions -
/cart/
/basket/
/checkout/
/my-account/
/orders/
/members/
/subscriptions/
/forums/
/courses/
/tickets/
/wp-login.php
/registration/
/wp-json/
/xmlrpc.php
/wp-..php
index.php
sitemap(_index)?.xml
/feed/
Cookie Exclusions -
comment_author
wordpress_[a-f0-9]+
wp-postpass
wordpress_no_cache
wordpress_logged_in
edd_items_in_cart
woocommerce_items_in_cart