Intro

Client-side cache can store files such as CSS and JavaScript for future use.

Therefore, after modifying such files, the browser may still use the outdated cached file.

To make sure that the most up-to-date version is in use, we can add a ?ver= parameter to the file’s URL when loading it.

For example:

<link
	rel="stylesheet"
	href="https://example.com/style.css?ver=25"
	type="text/css"
	media="all"
/>

When the value of the version parameter changes (let’s say from 25 to 26), the browser will download and use the new version instead of continuing to use the cached version.

While this version number can be changed manually whenever the file is changed, it can also be automated.

The timestamp of the file modification time will be used as the version.

This way the version will be updated automatically based on the last time the contents of the file were changed.

Let’s take a look at how this can be done using PHP, and then particularly in a WordPress environment.

PHP

The filemtime PHP function gets the timestamp of the last time the requested file was modified.

For instance, filemtime( 'style.css' ) will output something like 1652252901.

We can add this timestamp to the URL of the file as its version:

<link
	rel="stylesheet"
	href="https://example.com/style.css?ver=<?php echo filemtime( 'style.css' ); ?>"
	type="text/css"
	media="all"
/>

WordPress

In a WordPress environment, we should load the CSS/JS files using the dedicated wp_enqueue_style and wp_enqueue_script functions.

The fourth parameter in these functions is the ver parameter, where the version can be specified.

We’ll use there the same filemtime logic.

So loading a CSS file will look something like:

wp_enqueue_style(
    'style',
    get_template_directory_uri() . '/assets/css/style.css',
    array(),
    filemtime( get_template_directory() . '/assets/css/style.css' ),
);

And loading a JS file will look similar to this:

wp_enqueue_script(
    'script',
    get_template_directory_uri() . '/assets/js/script.min.js',
    array(),
    filemtime( get_template_directory() . '/assets/js/script.min.js' ),
    true,
);

References