WordPress Dev Tip – The Cache Breaker

Strange title I know (you will see why it is strange when you have read the post) – how many times do I say that? I think I need to ask my therapist why I come up with such titles 🙂

Anyway, on to the good stuff. The cache breaker and what I mean by this. Sometimes when you are working on a javascript or css feature on a site the changes you make aren’t visible when you reload the page – this is because of caching. Now arguably you should be doing all development on a staging site after launch and caching isn’t needed on a staging or pre-launch site, but we all know that sometimes we find ourselves developing in javascript or CSS with caching on, and it is a pain.

Do we either disable caching entirely or flush the cache each time, both equally unnecessary because there is a much easier way. All you need to do is use time() as the version number when enqueuing your script. Let me show you:

This means each time the page is loaded the script gets a new version number ?ver=x and so a new version of the file is served. If the url stayed static, either with the same version number or no version number, the javascript file’s cached version is served.

For reference the way to serve files without version number is to use NULL instead of time() in the example above, if you leave that parameter of wp_enqueue_script out the default behaviour is to use the version of the theme or plugin it is being enqueued by.

One final tip is if you want your users to continue to see the cached file for the sake of optimisation, but you want to break the cache you can use a parameter on the url.

Then you just add that param to your url i.e. https://mysite.com/?cache_breaker=break-cache or https://mysite.com/?var=other&cache_breaker=break-cache, and you will see the results of your latest changes every time. It is handy to do this if you are just nipping in to make a few css changes.

Like the code you see here? You can hire me at Codeable.io - a WordPress specialist outsourcing site that vets developers to make sure they are of the highest standard. See all developers you can hire through Codeable here.

Posted in Code Snippets, Help Topics, Wordpress and tagged .

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.