Whether you are building a business website or a personal blog, you may have to toss WordPress, due to various needs, you may install various caching plugins, such as WP Super Cache, W3 Total Cache, DB Cache Reloaded Fix, and Hyper Cache. After you install the theme, you may have to make some changes and update the CSS and JS files frequently. But these static files have been cached by the cache plugin, sometimes you can’t show the newly modified CSS and JS files on the front page immediately after you modify and upload the overlay.
Of course, you can delete the cache manually, but in case you modify it very frequently, it is still troublesome to delete the cache file manually. How can I get the visitor’s browser to get the latest CSS and JS files instead of waiting for the browser cache to expire and display the new files? There are generally the following methods.
Numeric version number
If you have some experience in web development, then it is not difficult to understand that we can use the version number parameter to control. That is, the original CSS file path code, for example, is as follows. https://www.yourdomain.com/wp-content/themes/themename/style.css
Then if the CSS file is updated, you can add a version number to it, i.e., change it to
However, in WordPress, if you have to update the version number manually every time you modify it, it is too tiring. How to make the version number updated automatically? (i.e. the number after? v= is added automatically)
Using PHP hooks, use wp_enqueue_style() function to hook up our custom function.
Add the following code to the theme’s functions.php file to automatically add a time version number to the styl.css file: // Add a timestamp version number to the CSS file
add_action( ‘wp_enqueue_scripts’, ‘webspei_realtime_css’ );
$css_file = get_stylesheet_directory() . ‘/style.css’;
wp_enqueue_style( ‘css-file’, get_stylesheet_directory_uri().’ /style.css’, NULL, filemtime($css_file) );
Above $css_file note to check if the path is the same as your theme’s CSS file. The above is written as style.css in the theme’s root directory as a stylesheet file.
The same for the js file: // Add a timestamp version number for the js file
add_action( ‘wp_enqueue_scripts’, ‘webspei_realtime_js’ );
$js_file = get_stylesheet_directory() . ‘/js/main.js’;
wp_enqueue_script( ‘js-file’, get_stylesheet_directory_uri().’ /js/main.js’, NULL, filemtime($js_file) );
Note that CSS files use the WP_enqueue_style function and JS use the WP_enqueue_script function.
By using the above method, you can ensure that every time your website users open the browser, they will access the latest css and js files after your changes, instead of using caching.
Of course, if you don’t toss CSS and JS too often, you can ignore the methods in this article.
Update: W3 Total Cache now comes with this feature.
Set it up under Browser Cache, as follows.