Simple Cache buster for WordPress

Bust it by Design.

Categories: Development, WordPress

As with the Simple Cachebuster for Laravel I found myself needing a way to invalidate a WordPress sites assets.

So as I did before, I opted to add a task to my gulpfile.js that will generate a file in the root of the site for me. /wp-cache-buster.php that simply contains a timestamp. The difference with this being that I don’t have a Docker build this time. This is run as the front end assets are compiled with Gulp.

The site that I’m working on happens to live on a Pantheon Elite server. One thing that I found interesting with Pantheon’s architecture is that it’s heavily Git and Workflow based. This means that the file systems are Read Only.

Part of what you get when you start to fine tune site speeds and performance is a love-hate for caching. Sure it’s fast but when you deploy an update. Things can be totally messed up. A simple way to combat this and look like a champ to those who can’t figure out how to clear their cache is to simply invalidate those pesky assets when you deploy the site.

First, you will need to install the File System package by typing npm install file-system --save

Next, add the following task to your Gulp build.

gulp.task('cache-buster', function(cb){
    fs.writeFile( '/lib/cache-buster.php', "<?php define( 'CACHE_BUSTER', " + new Date().getTime() + " );\n", cb );
});

In my case, I will be building the assets in my themes folder and outputting a file in the WordPress root.

How you call this Global variable is up to you. I opted to require the file from within /funtions.php file and in my theme added a helper function. For the most part, I don’t reply on enqueuing scripts because of the poor performance. But there is no reason you can’t tac it on in your code.

/**
 * Allows us to invalidate front end asset caching for various proxie caches.
 *
 * @param bool $raw Set to true, No query string will be output.
 *
 * @return int Date stamp
 */
function cache_buster( $raw = false ) {
    if ( defined( 'CACHE_BUSTER' ) and true === $raw ) {
        return CACHE_BUSTER;
    } elseif ( defined( 'CACHE_BUSTER' ) ) {
        return '?ver=' . CACHE_BUSTER;
    }

    return '';
}

I hope this was able to help you out and let me know how this worked for you!


Adam Patterson

Adam Patterson

User Interface Designer & Developer with a background in UX. I have spent 5 years as a professionally certified bicycle mechanic and ride year-round.

I am a husband and father of two, I enjoy photography, music, movies, coffee, and good food.

You can find me on Twitter, Instagram, and YouTube!