If you are working on developing a WordPress theme and you find yourself making numerous, rapid stylesheet or JavaScript changes but are frustrated when theupdates don’t show up on the web no matter how many times you force-refresh and empty your browser’s history, you’ve got cached files. Caching is a good thing, but when you want to see your changes, it can become a hindrance very quickly. This post addresses busting the cache when a file has been updated.

The solution is to intelligently cache stylesheets when they haven’t changed, but to reload them when they’ve been updated utilizing the PHP file modification time function filemtime(). Some CMSes do this natively (like Expression Engine), but WordPress doesn’t— yet.

You can add this functionality to your theme by modifying the stylesheet link in the header.php theme file as follows:

<link rel="stylesheet" type="text/css" href="<?php bloginfo('stylesheet_url'); echo '?' . filemtime( get_stylesheet_directory() . '/style.css'); ?>" media="screen">

If you have additional stylesheets or JavaScript files you’d like to apply filemtime() to as well, use the following syntax:

<?php $cachebustFile = '/your-subdirectory/your-file.ext'; ?>
<script src="<?php echo get_template_directory_uri(); echo $cachebustFile . '?' . filemtime(get_template_directory() . $cachebustFile); ?>"></script>

For more information, see Cache busting CSS files other than style.css, Prevent CSS Caching, or Smart Cache-busting for your WordPress Stylesheet.

Note: If you have downloaded my KM-H5 template theme after Dec. 31, 2011, this feature is already included in the core theme files.