What I was after
On a site that I had in beta, I was making (relatively) frequent changes to the CSS file, but had caching enabled on the server. So that visitors would benefit from always loading the most recent version of the page’s CSS (and not a stale copy that might have had a few unintended behaviours), I wanted to add a version number to the CSS file in my theme’s header.php file. I didn’t want to use the day’s date as the version number (a frequent Google solution), for example, as that could be taxing on the server, and I didn’t want to modify it manually every time I updated the CSS file. So it seemed that the easiest and best way would be a lightweight way of calling the file’s last modified date and appending it to the file name.
After a few searches, the best option for the way the site had been set up was the first result for “add file modified date to css wordpress”, which was Force CSS changes to “go live” immediately by Mark Jaquith. His solution is simple, automatic, and quick to apply.
The important bits
Of course, the code might change slightly based on how you have your stylesheets set up relative to your theme folder (so modify it based on where you have your CSS file stored and what you’ve named it), but in essence, simply replacing your normal <link rel=”stylesheet” href=”xyz.css” type=”text/css” /> with the following works like a charm:
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/styles/main.css<?php echo '?' . filemtime( get_stylesheet_directory() . '/styles/main.css'); ?>" type="text/css" />
The above generates the following call on the front end, notice the version number that I’ve bolded:
<link rel="stylesheet" href="http://YourDomain.com/wp-content/themes/YourTheme/styles/main.css?1467917567" type="text/css">
When a new main.css file is uploaded, the version number will change automatically and the visitor’s browser will load the most recent version automatically. Thanks, Mark!