The thoughts, opinions and sometimes the rants of Mark Evans

Simple Wordpress Caching Plugin

| Comments

I was hoping to spend this weekend doing nothing but playing Xbox and vegetating in front of the television but unfortunately Amazon let me down and my games weren’t delivered, this means that I have some time that I wasn’t expecting to have.

So I decided to work on a problem that has been bugging me for a few weeks, which is getting Wordpress to send proper Cache-Control headers so that I could utilise a proxy cache (other than varnish or nginx) to handle caching of the pages for my website.

I looked at the many cache plugins out there which do similar things but they are all massively complicated (IMHO) and tend to wrap multiple functionality into a single plugin, all I wanted to do was send cache control headers depending on the type of page being viewed.

My rules were simple

Frontpage –> 30 mins Post / Page –> 60 mins Category / Tag Page –> 120 Mins

If the user was logged in or an admin page was being displayed then I would obviously want to bypass cache for it to prevent anything bad from ending up in the proxy cache.

This actually turns out to be much simpler than I expected and by hooking into the ‘wp’ action you can send headers to control caching.

For example to send cache-control headers for 1 hour for all url’s if the user isn’t logged in or viewing an admin page

Simple Cache Header Plugin
    add_action( 'wp', 'send_cache_header' );

    function send_cache_header() {
      if (!is_user_logged_in() && !is_admin()) {
        $time = 3600;
        header('Cache-Control: max-age=' . $time . ', public, must-revalidate, proxy-revalidate');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');

I’m sure there is something I’ve missed here and I will be doing some proper testing next week but this is a much nicer way to deal with this problem than the beast which is W3-Total-Cache.

There is of course much more work to do, in order to add an options page to control the cache times etc and I’ll need a way to clear the proxy cache when a post changes, I will be working on all this functionality soon to complete the plugin.

This is currently quite specific to my needs but if anyone is interested once the project is completed I can look to make it more generic so others can use this as well, just send me an email or leave a comment here.