DEV Community

Cover image for Prevent browser caching of your stylesheet in WP.
SeanAUS120
SeanAUS120

Posted on

Prevent browser caching of your stylesheet in WP.

My workflow for Wordpress sites is to run a child theme and make all CSS changes in to the child style.css so it's neat.

Typically there will be server-side cache (Varnish) and frontend cache (W3TC plugin) where we run in to the problem that any changes to your style.css will never be seen by your customers. Browser cache is gobbling it up and often setting a 365 day lifetime on that file. How do we bust it?

$rand = rand( 1, 999999999 );
wp_enqueue_style( 'brisbane-css-bust', get_stylesheet_uri(), '', $rand );
Enter fullscreen mode Exit fullscreen mode

Throw the above in to your functions.php.

What we're doing here is re-enqueing the /child-theme/style.css file on every page refresh so it's not being cached.

get_stylesheet_uri() is referencing the child theme CSS file, not the main theme as we have the child theme activated (WP does this automatically).

$rand = rand( 1, 999999999 ); is adding a query string to the file so it appears new to the browser. A random number between 1 and 9,999,999 is selected which means it will always be unique.

Check your W3TC setup isn't cacheing this query string but it shouldn't straight out of the box.

Developed this tweak for these sites:
Presety Lightroom
Lightroom Presets
Brisbane Agency

Top comments (0)