Recently I saw a tweet conversation between @Norcross and @JPeterson about decaching css files when developing with WordPress. The solution is simple and something that WordPress even has built-in – however it’s also something that is easy to forget to turn on and off.
The suggested solution was to use the following when enqueuing css files:
function bm_enqueue_styles() {
wp_enqueue_style( 'MY-CSS-NAME', MY-CSS-FILE.CSS, array(), time(), 'all' );
}
The important part is the time()
function being used as the version number. Using this the css will be loaded clean on every page load. This is great when developing but when your code gets pushed out to production it is the sort of thing that can be forgotten about – which in this case would mean the css files will never be cached causing a performance hit. So is there a better way?
Enter WP_DEBUG
WP_DEBUG is a php constant used inside WordPress to enable error reporting to make things easier to debug. In my opinion all WordPress developers should be using this in their development environments. Switching it on enables PHP error reports – and displays messages when deprecated WordPress functions are being used. This means you can much more easily spot problems and make sure code is future proof.
It goes without saying that WP_DEBUG ‘should not’ be used in production environments. As such – when you’re developing it’s on, and when the site is live it’s off.
Note: This property should be added to your wp-config.php file
WP_DEBUG on
define( 'WP_DEBUG', true );
WP_DEBUG off
define( 'WP_DEBUG', false );
So how would I use it?
Firstly – I should point out something else I do in my themes. Instead of hard coding each version number for my custom scripts and styles – I use a php define. This then gives me a single place to clear cache for everything.
define( 'BM_VERSION', '1.0.1' );
function bm_enqueue_styles() {
wp_enqueue_style( 'MY-CSS-NAME', MY-CSS-FILE.CSS, array(), BM_VERSION, 'all' );
wp_enqueue_style( 'MY-CSS-NAME-2', MY-CSS-FILE-2.CSS, array(), BM_VERSION, 'all' );
}
Once you see this the solution should be obvious.
if ( WP_DEBUG ) {
define( 'BM_VERSION', time() );
} else {
define( 'BM_VERSION', '1.0.1' );
}
// other code and stuff ...
function bm_enqueue_styles() {
wp_enqueue_style( 'MY-CSS-NAME', MY-CSS-FILE.CSS, array(), BM_VERSION, 'all' );
wp_enqueue_style( 'MY-CSS-NAME-2', MY-CSS-FILE-2.CSS, array(), BM_VERSION, 'all' );
}
I must admit – before Norcross tweet I hadn’t considered using this for css file decaching – but I’ve now added it to the theme I’m running here on Binary Moon and it does make the process a little simpler.
Was it good/ useful/ a load of old rubbish? Let me know on Mastodon, or BlueSky (or Twitter X if you must).
Link to this page
Thanks for reading. I'd really appreciate it if you'd link to this page if you mention it in your newsletter or on your blog.