Force a CSS Refresh in WordPress

Published by Leave your thoughts

WordPress Development for clients can have a number of different common problems. One I run into a lot is when clients don’t do a hard refresh, and so don’t get the latest changes I made in their CSS Stylesheet (Yes, “Cascading StyleSheet Stylesheet” =D).

Many browsers cache the stylesheets of websites they visit as they rarely change. But what do you do if you update a WordPress Stylesheet and need visitors to grab the latest version?

The easiest way to force all browsers to get the latest version of CSS without a hard refresh is to change the URL of the file, so that browser thinks it’s a brand new file.

$theme = wp_get_theme();
wp_enqueue_style( 'child-style', get_stylesheet_uri(),
    array(),
    $theme->get('Version') 
);

This code to enqueue WordPress Stylesheet into your site will grab the version from your WordPress stylesheet and add it to your URL, so every time you update your Theme version number in your WordPress css file, you’ll force refresh of all visitors!

My CSS file’s header file says:

 Version:      1.0.1

So my theme code now says:

<link rel='stylesheet' id='child-style-css'  href='/wp-content/themes/theme-name/style.css?ver=1.0.1' type='text/css' media='all' />

Enjoy,
Ashton

Categorised in: CSS, Webmaster, Wordpress

This post was written by Ashton