Major CSS Changes, Force Browsers To Grab New Stylesheet on WordPress Website
I did a major overhaul on a WordPress site recently. All the changes were done in a staging environment and the main stylesheet was completely overhauled. The release of the new site went perfectly except for one issue: this site used major caching to decrease load times. I attempted to force clear the cache many times from my Cloudflare CDN control panel but certain devices just wouldn’t grab the new file.
I tried explaining to the client what was going on and while they understood it was a valid concern that this may be occurring to other visitors as well who frequently visited their site. So what could I do?
Assign versioning to the stylesheets using wp_enqueue_style!
Previously, I had declared the stylesheets within my functions.php file without adding a version. For example:
wp_enqueue_style( 'style-css', get_template_directory_uri() . '/css/style.css');
However, there are additional parameters that can be declared using wp_enqueue_style including:
Dependencies – these are other stylesheets that this stylesheet needs before it can load. For example, if you want bootstrap.css to load prior to style.css, bootstrap.css could be a dependency.
Version – this allows us to specify a version of the file such as 1.0, 1.5, 2.0, etc. (more on this in a second).
Media – This allows us to specify which screen size the file should be loaded on such as max-width:767.
So in order to fix my problem today, let’s add a version to our wp_enqueue_style function. It’s pretty simple:
wp_enqueue_style( 'style-css', get_template_directory_uri() . '/css/style.css', array(), '2.0' );
As you see, I’ve declared a blank array for the dependencies, as there’s nothing this stylesheet depends on in this case. I’ve then added a version number to the next parameter. Just like that, browsers notice that the version of the stylesheet has changed and they are forced to grab the newest version when a user accesses the site.