Cache busting – a variation for enqueued files

Long long ago in the mists of time there was born a technique for that most annoying of minor issues , cached files not updating when changes are made to parent file.

Then it was a simple of matter of making the browser believe or the server pretend that we now had a new file so the browser cache would in a sense be redundant and the new file downloaded this was brought about by appending a query string to the end of the file e.g style.css?ver=v1.1 simple but effective.

Now in reality there are many means we should perhaps approach this aspect of caching through file header or cache headers a sophisticated means of sending file information to the browser with instructions on how to deal with the file, but this method of appending a string to the file name works pretty well.

Buddypress introduced a $version = '' to append to files in their enqueue function this allowed devs to manually change this value to force the cache to refresh.

I have used a variation of manipulating cache headers and / or adding dynamic version strings using the getlastmod () function in php for a while where needed and while working on a new child theme for the BP community I considered the requirements for the themes enqueue function and how BP was setting theirs manually.

My re-working of this approach for the child themes enqueue functions was to write a function to programmatically fetch the files last modification details based on changed data blocks in the file.

// Cache busting dynamically
function get_file_last_mod($filename) {
 $filename = dirname(__FILE__) . '/_inc/css/' . $filename;
  if( file_exists($filename) ){
   $version =  date ("M d Y H:i:s.", filemtime($filename));
   // manual cache busting
   $version = 'V1.0';
  return $version;

The function takes a file name parameter and then finds the path to that file name, we then pass that absolute path to the php function filemtime() to determine if file blocks have changed this in turn is passed back to the date function to produce a date string to append to our file (N.B. the version shown here is for WP/BP and the wp_register_style function which adds the required ‘?ver=’ so for non WP applications one would want to add something like $version = '?ver=' . date ("M d Y H:i:s.", filemtime($filename));

To call the function we simply add the function into the WP register function into the position that sets the file version string:

wp_register_style( 'ourfilename',  get_stylesheet_directory_uri() . '/_inc/css/ourfilename.css', array(), get_file_last_mod('ourfilename.css') );

Now we have a file stamp giving us month, year, day, & time of the file last modification which will update itself automagically.

For safety I do a if( file_exists( $filename ) else lets set a manual string which can be manually altered if for any reason the path to file isn’t or can’t be found?.

Comments are closed.