Force browsers to load the latest CSS and JS versions in WordPress

During the development of a website, the caching of .css and .js files can be a problem, especially when dealing with less tech-savvy clients who do not understand that the changes you made might not be visible to them due to their browser caching previously downloaded content.

Adding a parameter to the end of the .css and .js files solves this problem as the browser is forced to re-download the file if it did not encounter the parameter value before.

The best solution seems to be adding the file modification date as the parameter, so whenever you modify the file, the parameter will change automatically.

To implement this in WordPress, put these two functions in your theme’s functions.php:

 // Always fresh css includer  
 function insertCss($file) {  
      $cssFile = get_bloginfo('template_directory') . '/' . $file;  
      $cssFilePath = get_template_directory() . '/' . $file;  
      $csstime = @filemtime($cssFilePath);  
      return $cssFile . '?v=' . $csstime;  
 // Always fresh js includer  
 function insertJs($file) {  
      $jsFile = get_bloginfo('template_directory') . '/' . $file;  
      $jsFilePath = get_template_directory() . '/' . $file;  
      $jstime = @filemtime($jsFilePath);  
      return $jsFile . '?v=' . $jstime;  

In the header use them like this:

<link rel="stylesheet" href="<?php echo insertCss('style.css'); ?>" type="text/css" />
<script type="text/javascript" src="<?php echo insertJs('js/functions.js'); ?>"></script>

No more angry calls demanding a change you already made…

Related Posts

Sorry, no similar posts found.

Leave a Reply

Your email address will not be published. Required fields are marked *