WordPress Logo

in Tutorials

How to Tell the Browser Not to Cache your WordPress CSS and JS Files

For WordPress theme creators, browser and server cache can sometimes be a problem when making constant changes to your CSS and JavaScript files. You could always press Shift+F5 on your browser to reload the cache, however, not all your returning site visitors know this and when they come back to your site after you’ve made updates to the stylesheet, they may not see your latest changes.

The Solution

To work around this, there’s this neat trick in WordPress that will tell the browser to always reload the cache and grab the latest stylesheet or JavaScript file. You only need to modify the lines in your functions.php where you enqueued the CSS and JS files.

wp_enqueue_style( 'theme-styles', get_stylesheet_directory_uri() . '/style.css', array(), filemtime( get_stylesheet_directory() . '/style.css' ) );
wp_enqueue_script( 'custom-js', get_template_directory_uri() . '/js/custom.js','', time() );

What it does

The code above will append a ‘?ver=‘ parameter with the timestamp of when a file was modified. When browsers see a change in a file’s URL parameter, they will treat it as a new file and redownload it to the cache. This will essentially make the browser reload the cache every time you’ve made changes to the files.

Write a Comment