All right, so we’re probably all familiar with the typical way to ensure that your main CSS file is refreshed when you load the page (busting the browser cache), right?
<link rel="stylesheet" type="text/css" media="all"
href="<?php echo get_stylesheet_uri();
echo '?'.filemtime( get_stylesheet_directory() . '/style.css'); ?>" />
I need to do the same thing on another CSS file. Yes, my style.css file has its own set of @import “css/myFile.css” which are working fine, but humor me, if you will.
So, back to header.php, right after that first link, and before the call to wp_head():
<?php $cssFile = get_stylesheet_directory_uri().'/css/other.css'; ?>
<link rel="stylesheet" type="text/css" media="all"
href="<?php echo $cssFile; echo '?'.filemtime($cssFile); ?>" />
And this leads to a warning (as part of the href attribute of the link when the browser gets the page):
Warning: filemtime(): stat failed for http://localhost/wordpress/wp-content/themes/my_theme/css/other.css
the path to the file seems to be built correctly (and the other.css file is there), but filemtime (stat, actually) fails on it. How come?
Other recommended ways to include the ‘latest’ version of a CSS file other than style.css?
Should I go with wp_register_style instead? If so… how can I tell wp_register_style to bust the browser cache (ie: get me the latest version of the css file, even if the browser has it cached)?
Thanks in advance
You’re using the file’s path in the first call, but its URL in the second. So it won’t work.
I tend to just enqueue the main stylesheet using
wp_enqueue_style
, and append something to the version when i want to prevent caching..When i want to stop caching i update
$ver
to something that will constantly change, such as the time..Or something similar..
Here is the code I have from an unreleased CDN plugin I have. It will automatically replace the ver query_var that the enqueue functions use with the file time:
If you’d prefer not to use the standard
style.css
file for your WordPress theme’s CSS cache-busting technique, here’s a complete working code example:Would result in the following HTML output:
For terseness of this example, I excluded
rel="stylesheet" type="text/css"
on the<link>
element, so be sure to add those attributes to your final markup.I wrote my own little function as a plugin for jobs like this. It take two paramters, the path that will need to be appended and a date format. Here is a sample usage…
which would result in http://pewsocialtrends.org/wp-content/themes/pew-socialtrends/css/reset.css?2010-11-11_6:47:45
Here is the code:
Simple: use the URl to load the style and the path to get the
filemtime()
:The resulting URl will be something like