When developing a WordPress theme, I often need to ensure I’m loading the latest version of the CSS file I’m working on. One way to do this is by appending a URL parameter (e.g. ?ver=123
) that gets updated each time the file gets updated.
Load Newest Assets Plugin
Thanks to Corey Salzano for pointing out the Busted! plugin on Twitter. This plugin will check the last modified date of all of the assets you load (JavaScript and CSS) and adjust the version URL parameter to load the latest version.
My Code
Because I find this code interesting, I’m going to leave it as part of this post but for most people I’m guessing the Busted! plugin is a better solution.
We can automate updating the version URL by using the last modified time for the file in Unix Time (the number of seconds since January 1, 1970). This code will do just this.
You can add this code to your functions.php
file in your theme (or even better, put it in the mu-plugins directory).
Preferred Install
- Navigate (or create) the mu-plugins directory
- Run the following from the command line
Run from Command Line
curl -O https://gist.githubusercontent.com/salcode/b627efd3122155e657688914dfaa298f/raw/add-file-mod-time-as-ver-number-to-css.php
<?php | |
/** | |
* Filter all CSS URLs being loaded on the page. | |
* Add the last modified time (in Unix Time, i.e. a large integer) | |
* to the end of the URL. | |
* | |
* This forces the browser to load the most recent version of this file. | |
* e.g. http://example.com/wp-content/my-child-theme/style.css | |
* becomes | |
* http://example.com/wp-content/my-child-theme/style.css?ver=1533080875 | |
* | |
* Quick Setup: | |
* 1. Navigate (or create) the mu-plugins directory | |
* 2. From the command line run | |
* curl -O https://gist.githubusercontent.com/salcode/b627efd3122155e657688914dfaa298f/raw/add-file-mod-time-as-ver-number-to-css.php | |
*/ | |
add_filter( 'style_loader_src', function( $src, $handle ) { | |
// All of my CSS changes are made in a child-theme. | |
if ( 'child-theme' !== $handle ) { | |
// This is not the child-theme CSS file, make no changes. | |
return $src; | |
} | |
// Use the default location for the child theme CSS file. | |
$file_path = get_stylesheet_directory() . '/style.css'; | |
if ( ! is_file( $file_path ) ) { | |
// No file exists in the default child theme CSS file location. | |
// Make no changes. | |
return $src; | |
} | |
$last_modified = filemtime( $file_path ); | |
$src = add_query_arg( 'ver', intval( $last_modified ), $src ); | |
return $src; | |
}, 9999, 2 ); |
Leave a Reply