Child Theme Browser Cache

One of the most common niggles I encounter when working on WordPress websites is the clients browser cache not allowing them to see the latest updates to style sheets.
“Can you just do a hard reload – Ctrl and f5 please…” – What a pain! Especially if your client is a real technophobe.
The issue arises because of browser caching. This is really useful once our website is live. It is however, really frustrating during production.
Here are a couple of solutions you can use to overcome this WordPress issue.

1. Add the current time as version number

This article assumes you are familiar with creating a child theme. As a reminder – when using a Child Theme you should enqueue your styles and scripts. For more information on using child themes correctly see the WordPress Theme Handbook.

In our child’s functions.php file we need to add a little extra code which will add a timestamp to our enqueued style sheet. Typically our style sheets will be added to the head of our site and appear like this:

<link rel='stylesheet' id='child-style-css' href='' type='text/css' media='all' />

What we are interested in is the version number. In the above example ‘ver=1.0.1’ is our version number. We can change this number. This in turn will force the browser to reload the style sheet rather than load the old version from cache. We do this by using the php function filetime(). The piece of code below will achieve this by adding the filetime as the version number.

add_action( 'wp_enqueue_scripts', 'tcg_enqueue_styles' );
function tcg_enqueue_styles() {

$parent_style = 'yourtheme-style';

wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ), filemtime(get_template_directory() . '/style.css'), false );

When the style sheet is hooked into the head of our website it will now look something like this:

<link rel='stylesheet' id='child-style-css' href='' type='text/css' media='all' />

Now, each time we update our CSS and save, the version number changes using the time the file was modified/saved. This is my preferred method of getting around the browser cache. It may seem a little long winded just to avoid having your client hard reload their browser however, the above code snippet takes only seconds to add.

IMPORTANT: Remember to remove the filetime addition when turning your website to production from development!

Leave a Comment