Stop CSS Caching After a Change in WordPress

CSS Carved Pumpkin

If you’re in the process of developing a WordPress theme, browser caching isn’t necessary and it can be a pain because your theme won’t always update after you have made a change. On the other hand caching plays a crucial role in the speed and download times of websites. So what are we to do? In WordPress it’s actually very simple, if you know what you’re doing, to set up a function to force the browser cache into re-downloading the CSS file again. Depending on your level of PHP knowledge, there is a plugin already built for this task called CSS Cache Buster, or you can write your own function.

All the code for doing this yourself can be found on Alister Cameron’s website which is what my code is based on.

Functions.php

// Stop CSS Caching
function stop_css_caching()
{
	$split = explode("wp-content", get_bloginfo('stylesheet_url'));
	return get_bloginfo('stylesheet_url') . "?" . filemtime(ABSPATH . "/wp-content" . $split[1]);
}

This function basically takes the URL of the default stylesheet and adds the time modified variable to the end of it.

Header.php

<link rel="stylesheet" type="text/css" href="<? echo stop_css_caching() ?>">

The browser will see this as a different stylesheet and download it again and show your recent change.