Maybe this situation sounds familiar to you: you have been working on your local environment on a plugin or theme for a WordPress site, you pushed your changes and deploy on your server.
Then you access the server and can’t see the changes because your browser cached the previous version, so you need to delete the cache or doing a hard refresh to see the content.
Now imagine explaining a client that they need to do a hard refresh (and how to do it) to see the changes. Is not your favourite situation, isn’t?
Well, let me tell you this a TYPICAL problem the web developers and agencies face all the time. And the solution to this problem it’s super simple.
First of all, let’s think about the problem and a possible solution.
The problem: we should use the same file name for our assets (css/js/img) but seeing the new version each time we upload/update that file into the server.
The approach to a solution: we need to add a unique parameter to the file name. For example style.css?ver=123456789. All the “magic” happens in getting a unique value for each file every time we update them.
A possible solution (spoiler alert: this is not the best solution): if we are using GIT in our project, we can add the last commit at the end of each file, for example, style.css?ver=b576fd7.
(To learn how to get the last GIT id in PHP, see this answer on StackOverflow)
What’s wrong with this solution? The no so important stuff is: not every project uses GIT (I know we are almost in 2020 and some people don’t use GIT yet.). As I said that is not really important. The most important part of that solution is that if you change something in functions.php, to give some example, you are going to have a new GIT id, so you are forced to reload the assets to your visitors, even when you are not changing any of them.
A good solution: a really good and simple solution to this problem is to think really “deep” in the file. We know that filename is not going to change each time we update the file, but what is going to change every single time we update the file? You are right! The timestamp of the last time it was updated, so that is unique and it’s going to change each time we update the file.
In terms of code should be:
If you add that few lines of code to your functions.php file, you are going to start using the versioning method to all your CSS and JS files added via wp_enqueue_script or wp_enqueue_style functions.