In WordPress, you add theme styles and scripts using the trusty wp_enqueue_script and wp_enqueue_style methods. However, by default, your enqueued scripts and styles will be added to your WordPress site as straight scripts.
What happens (and the reason you’re probably here) is the browser will cache your scripts, which is what we want to happen.
There is nothing more frustrating than making a change, only for the client or QA team to say they can’t see the changes, for you to go back then and tell them to do a “hard refresh.”
What we want to happen is for the version number to change on our scripts and styles, ONLY when they change. We want the browser to cache our files because it takes the load off of the server (or CDN).
To determine when a file has been updated, we can use the PHP method filemtime, which will return the UNIX timestamp of when a file was last updated.
For the wp_enqueue_script and wp_enqueue_style methods, the fourth argument is the version number which is where we will use the filemtime function to auto-generate a version number for us.
wp_enqueue_script('theme-js', get_stylesheet_directory_uri() . '/assets/js/theme.js', array(), filemtime( get_stylesheet_directory() . '/assets/js/theme.js'));
In this example, we require a file called theme.js from assets/js. Whenever this file changes, the filemtime value will change as well.
For styles, it looks pretty much the same:
wp_enqueue_style ('theme-css', get_stylesheet_directory_uri() . '/style.css', array(), filemtime( get_stylesheet_directory() . '/style.css'));
With these simple changes, WordPress will cache bust our files when they change and the browser will cache accordingly. No more file cache mismatch issues!