If you have ever pushed an update to your WordPress theme’s CSS or JS files and then bang your head on your desk in frustration after going through the process of clearing every single one of the trillion different caches setup because it’s not reflecting the change on the live site. This is for you.
Version Numbers Are Your Friend
Behold, there is a better way! Both
wp_enqueue_style functions provide a parameter for the file’s version number. This number is then used as a query parameter in the reference URL. When this number changes, the cache gets busted.
Now sure, you could just remember to update this number every time you edit the file or subsequent files. Or, you could save yourself even more time by automatically having this number update itself whenever the file is modified via the ol’ timestamp method — now you’re thinking like a programming wizard! 🧙♂️
The Timestamp File Versioning Method in PHP
PHP has a built-in function (all the way back since PHP 4.0) called
filemtime that will return a file’s latest modification date. By default, it returns this date as a unix timestamp number. Since this timestamp is a cumulative number, we can use this as our file version number without a problem. Bingo! Here’s what that looks like combined with the WordPress enqueue script function:
$js_file = get_template_directory_uri() . "/js/main.js"; wp_enqueue_script( "my-js", $js_file, , filemtime($js_file), true );Code language: PHP (php)
Of course, you’ll want to replace the above code’s file location/name with yours. Now stop wasting time trying to clear caches and get back to making that awesome website!