Sometimes, after editing CSS or JS files on your WordPress site you might notice that the changes doesn't have any effect when viewing the site in your browser.

This is most likely due to "browser caching".

What's browser cache?
The way browser caching works is that files are stored in your browser, so that the next time you visit the same page, you won't have to download the same files again. 

This is smart and desirable since it saves on bandwidth and speeds up consecutive page visits.

So what's the problem?
The problem is that when you edit any of the files that are now stored in your visitors' browsers, they won't see any of the changes you make. 

This can sometimes be an annoyance when you are trying to make changes to your website's design, but there are smart ways to handle this situation...

Enter "cache busting"
Cache busting solves the browser caching issue by using a unique file version identifier to tell the browser that a new version of the file is available.

One common way to utilize cache busting is to use query strings with a version number.

Example:

https://example.com/style.css?ver=1
https://example.com/style.css?ver=2
https://example.com/style.css?ver=3

 All query string variations will be treated as separate files in the browser.

Cache busting in WordPress
WordPress already has these query string with version number built in.

You can for instance manually change the version of your theme or child theme by changing the version number in your theme's style.css file.

Automatic cache busting in WordPress
There are also smart ways you can have the version number of a CSS file updated automatically, each time you make any changes to the file.

To do this, we can enqueue our CSS file and set the version of the file to the time when the file was last edited.

Here's one way to do that:

function templ_cache_busting_enqueue_styles() {
  $cssFileTime = date( "YmdHi", filemtime( get_stylesheet_directory() . '/my-css-file.css' ) );
  wp_enqueue_style( 'my-css-file', get_stylesheet_directory_uri() . '/my-css-file.css', array(), $cssFileTime );
}
add_action( 'wp_enqueue_scripts', 'templ_cache_busting_enqueue_styles' );

Simply add the code above to your theme's functions.php file, and put any custom css in my-css-file.css or change the name/path of the file in the snippet yourself.

Did this answer your question?