How to Ensure Static Resources in WordPress are Updated Correctly When Using our Static Cache

All sites have caching of static files enabled by default, as it should be. But when you update the files, you may encounter that the updates are not visible. This is because they are delivered from cache, and not from the actual files. The solution for this is simple.

Use query strings (url strings)

In WordPress, the correct way to load a static resource is to use the enqueue functions. Enqueue scripts for Javascript, and Enqueue Styles for CSS. When you enqueue a file, you can add a query string to the file using the $ver  parameter and is where the magic happens.

How to enqueue styling files (from the WordPress documentation)

wp_enqueue_style( 
string $handle, 
string $src = '', 
array $deps = array(), 
string|bool|null $ver = false, 
string $media = 'all' 
);

$handle

(string) (Required) Name of the stylesheet. Should be unique.

$src

(string) (Optional) Full URL of the stylesheet, or path of the stylesheet relative to the WordPress root directory.

Default value: ”

$deps

(array) (Optional) An array of registered stylesheet handles this stylesheet depends on.

Default value: array()

$ver

(string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added.

Default value: false

$media

(string) (Optional) The media for which this stylesheet has been defined. Accepts media types like ‘all’, ‘print’ and ‘screen’, or media queries like ‘(orientation: portrait)’ and ‘(max-width: 640px)’.

Default value: ‘all’

How to enqueue styling and making sure the cache will be updated

The important part, and the part that makes sure you do not use the outdated, cached, version of a stylesheet is the $ver  part of the enqueue function. By setting $ver  to the timestamp of the file you are enqueueing, by using filemtime() , you make sure that if you update that file, WordPress will add the timestamp if the file(the time of the update) as a query string and the cache will be bypassed (and the new version will be cached).

Here is how you do it

wp_register_style( 'somehandle', get_template_directory_uri() . '/assets/css/master.css', false, filemtime(dirname(__FILE__) . '/assets/css/master.css') );

The file will now be loaded with a url looking something like this:

https://yourdomain.com/wp-content/themes/yourtheme/assets/css/master.css?v=1546694759

Next time you update your stylesheet, it will be bypassed by the cache immediately.