WordPress automatic cache update for the css file

When developing WordPress theme or working on customization for a client you often need to make incremental updates to the css file. Trouble is that the browsers caches the css files and you can’t see what you did on the the spot. If you know the pain, well, there is a solution.

First, I hope you are not including the css files directly in the header. It’s not the “WordPress way” – you should add the css files (and JS files as well) via the functions.php file using wp_enqueue_style. This would be a very basic load for the css file named style.css:

wp_enqueue_style( 'style', get_stylesheet_uri() );

Of course, this wouldn’t work just by inserting the code in the functions.php file, you need to put inside a function and call it when the header is displayed. To do this we create a function and add_action( ‘wp_head’, ‘name of the function’,0). For example:

function add_our_scripts() {

if (!is_admin()) { // Add the scripts, but not to the wp-admin section.
wp_enqueue_style( 'style', get_stylesheet_uri() );
} // end the !is_admin function
}

add_action( 'wp_head', 'add_our_scripts',0);

Now, that we have the stylesheet properly inserted, we still have the issue that the browser doesn’t update the layout as soon as we make a change in css file. What you would need is to change the name of the css file each time you make a change to the file, which is not that easy. But there is a trick, you can update the version of the file, by adding a version parameter, for example style.css?ver=1608362888 then you only need to increment the version each time. It’s still not a very easy way to update the css file so we need to bring in the big guns.

Let’s see that parameters can we use with wp_enqueue_style:

wp_enqueue_style( $handle, $src, $deps, $ver, $media );

Aha, so the forth parameter is the version. If we increment this parameter automatically we are all done. And yes we can do this in php with filemtime(). The filemtime() function returns the last time the file content was modified so if we make filetime from the css file it will replace the forth parameter with the time when the css file was updated the last time. Let’s do this:

function add_our_scripts() {

if (!is_admin()) { // Add the scripts, but not to the wp-admin section.
wp_enqueue_style('mainstyle', get_stylesheet_uri() , array(), filemtime(get_template_directory() . '/style.css'), false);
} // end the !is_admin function
}

add_action( 'wp_head', 'add_our_scripts',0);

Sweet. This way, each time you save the css file the browser will think it’s a new file and display the changes on a simple refresh.