How to Tell Browsers Re-update CSS/JS files when Files are Changed in WordPress?


In wordpress headers, you probably notice the CSS and JS static assets are referenced like this:

https://justyy.com/wp-content/themes/twentytwelve/style.css?ver=4.4.2

The query string ?ver= is used to tell browsers to do a force-update on the static resources when wordpress core version has changed because some browsers might not be able to ignore the cache files since the URL hasn’t changed.

Sometimes, I want to change the style.css in the child theme but the browser is still fetching the cached file since the wordpress version has not changed. and I have to go to CloudFlare to purge the cache. A better solution is to change ?ver= to ?filetime= so that everytime the file has been modified, the URL changes.

You can add the following into the child-theme functions.php template to make this happen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function justyy_remove_cssjs_ver( $src ) {
  $newsrc = $src;
  if( strpos( $newsrc, '?ver=' ) ) {
    $newsrc = remove_query_arg( 'ver', $newsrc );
  }
  $rootdir = '/var/www'; // the path to your domain on the server
  $url = parse_url($newsrc, PHP_URL_PATH);
  $source = $rootdir .'/'. $url;
  if (is_file($source)) {
    $newsrc .= "?m=".filemtime($source);
    return $newsrc;
  }     
  return $src; // keep unchanged if file is not accessible.
}
add_filter( 'style_loader_src', 'justyy_remove_cssjs_ver', 10, 2 );
add_filter( 'script_loader_src', 'justyy_remove_cssjs_ver', 10, 2 );
function justyy_remove_cssjs_ver( $src ) {
  $newsrc = $src;
  if( strpos( $newsrc, '?ver=' ) ) {
    $newsrc = remove_query_arg( 'ver', $newsrc );
  }
  $rootdir = '/var/www'; // the path to your domain on the server
  $url = parse_url($newsrc, PHP_URL_PATH);
  $source = $rootdir .'/'. $url;
  if (is_file($source)) {
    $newsrc .= "?m=".filemtime($source);
    return $newsrc;
  }     
  return $src; // keep unchanged if file is not accessible.
}
add_filter( 'style_loader_src', 'justyy_remove_cssjs_ver', 10, 2 );
add_filter( 'script_loader_src', 'justyy_remove_cssjs_ver', 10, 2 );

You could use file content.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
391 words
Last Post: How to Optimize All Images for All Your Websites on the Same Server using Single Command?
Next Post: The C# Simple Command Line Parameters Reader

The Permanent URL is: How to Tell Browsers Re-update CSS/JS files when Files are Changed in WordPress?

Leave a Reply