Last Updated: February 25, 2016
·
666
· thorbrink

Better version numbers for scripts and styles in WordPress

When registering and queuing scripts and styles in WordPress you can avoid the extra e-mails to clients explaingin how to clear the browser cache by implementing the version parameter as in the code below.

This sets the version number of the file to a timestamp of when the file was modified most recently.

A fallback to '1' is also implemented just for those times when you are a bit too fast and specify the path to the file incorrectly.

$handle         = 'my-js-file';
$src            = get_bloginfo('template_url') . '/file.js';
$dependencies   = array();
$version        = (file_exists(__DIR__.'/file.js')) ? filemtime(__DIR__.'/file.js') : 1;

wp_register_script(
    $handle,
    $src,
    $dependencies,
    $version // Is set to the file's modified time or 1 as a fallback.
);

1 Response
Add your response

It's a good idea, but you should be aware that it could hurt performance just a little... it shouldn't be an issue on most cases (and you can always count several ways to improve performance) but if your host/server uses a networked filesystem, it might make a difference

over 1 year ago ·