Cache busting CSS and JS assets in WordPress

Today we are going to learn about cache busting CSS and JS assets in WordPress the easy way.

Have you ever struggled to make sure updated versions of your CSS or JavaScript assets are being sent to users of your WordPress website? One way of solving this problem in the past, was to give each asset a unique name after updating it, forcing browsers to grab the new version when users visited your website. If you have ever done this, you will know it is a tedious process. Thankfully there is a much easier way by using the file meta data for each assets and the handy PHP function filemtime.

WordPress gives us the tools out of the box, to append unique version numbers to our CSS and JS assets, in the form of a query string. The wp_enqueue_style and wp_enqueue_script functions have a version parameter. With the use of the filemtime PHP function, we can automate the entire process by passing the file modified string as the value for the version parameter.

The filemtime function returns the file modified time from a files meta data. By using the $ver parameter of both the wp_enqueue_style and wp_enqueue_script WordPress functions, we can append the file modified time to our CSS and JS asset URLs.

The method for adding the file modified time to your stylesheets is shown below.

wp_enqueue_style(
  'theme-styles', // $handle
  get_bloginfo( 'stylesheet_url' ), // $src
  array(), // $deps
  filemtime( get_stylesheet_directory() . '/style.css' ) // $ver
);

The method for adding the file modified time to your scripts is shown below.

wp_enqueue_script(
  'theme-scripts', // $handle
  get_template_directory_uri() . '/js/scripts.js', // $src
  array( 'jquery' ), // $deps
  filemtime( get_template_directory() . '/js/scripts.js' ), // $ver
  true // $in_footer
);

This method of cache busting CSS and JS assets in WordPress means you will never have to worry about users not seeing updates you have made.

References