WordPress Cache Buster – Busted – New Cache Buster

Wow, I know I haven’t blogged twice in 2 days for maybe 10 years, but I had to – Josh Pollock just blew my mind with this tweet. Not with the main content of the post, which is greatly enjoyable to me as I try to buffer my backend skills with staying up to date with frontend tech, but because he really gave me a way to blow my cache-busting solution out of the water — busting my cache buster.

Some of you may remember (vain to even think so?) my blog post from back in August where I suggest using PHP’s time() function (which generates the current time in unix timestamp format) in the version parameter of the wp_enqueue_* functions to stop WordPress from serving cached versions of a given script or stylesheet. Then reading the code of Josh’s Gist (L13 block.php), I see he is actually going one further and using filemtime() instead of time(). Filemtime shows the last time the file was modified, so using this WordPress will show a cached version of the file, as long as the modified timestamp doesn’t change; change the file and your changes will become the cached version. Very clever.

That being said I have experienced problems using filemtime in the past so I would go even further and make a function like this:

That function checks that filemtime can be called and that the unix timestamp being returned isn’t a failure (if a call for a timestamp fails it usually returns the base timestamp of 1970-01-01 00:00:00).

Then you can use my wp_cache_buster function it in your wp_enqueue_* functions like so:

Eh voila. Any problems with any of the above please do let me know. I will try to find time to create a more complete example as a Gist.

Like the code you see here? You can hire me at Codeable.io - a WordPress specialist outsourcing site that vets developers to make sure they are of the highest standard. See all developers you can hire through Codeable here.

Posted in Code Snippets, Featured, Help Topics, Wordpress and tagged , .

Leave a Reply

Your email address will not be published. Required fields are marked *