Best way to clear static resources cache in WordPress

Have you ever come across the situation when you need to hard refresh the browser or open in the private mode of browser, even to verify the small changes in styles or scripts? I bet you have.
How to clear static resources cache? After implementing the code snippets shown below, you will be able to clear the cache automatically for every changes in static resource. 

Best way to clear static resources cache in WordPress

This can be even more painful when you are using the cache plugins or CDN for managing static resources. You have to manually navigate to plugin setting and clear the cache. And if you are using the CDN, you need to login to CDN account first and clear the cache from there manually.

Keeping apart the CDN cache, popular modern browsers stores the cache for better site speed experience. So, even when developing the website locally, your changes may not be reflected immediately.

Versioning is the KEY

You can clear the static resources cache with addition of little bit of code. While registering the static resources (Both Styles and Scripts), we will use pHp function filemtime() to get the timestamp of file changed time.

We will use the time returned by filemtime() as the versioning of static resources. So, basically every time we make the changes in CSS/JS file, WordPress will append the current timestamp to the changed files link. Then, Browser will interpret the changed file as the new file and load the updated contents.


//PLUGIN_ABSPATH means the absolute path of current plugin directory 

$main_css_filename = 'assets/css/main.css'; //Name of the CSS file
wp_register_style( 'main-style', plugins_url( $main_css_filename, __FILE__ ), [],filemtime( PLUGIN_ABSPATH . $main_css_filename ) );
wp_enqueue_style( 'dnog-main-style' );

$main_js_filename = 'assets/js/main.js'; //Name of the JS file
wp_register_script( 'main-script', plugins_url( $main_js_filename, __FILE__ ), ['jquery'],filemtime( PLUGIN_ABSPATH . $main_js_filename ), true );
wp_enqueue_script( 'main-script' );

And the same implementation can be applied in theme as well.

$main_css_filename = 'assets/css/main.css'; //Name of the CSS file
wp_register_style( 'main-style', get_template_directory_uri(). '/'. $main_css_filename, [],filemtime( get_template_directory() .'/'. $main_css_filename ) );
wp_enqueue_style( 'main-style' );

$main_js_filename = 'assets/js/main.js'; //Name of the JS file
wp_register_script( 'main-script', get_template_directory_uri(), ['jquery'],filemtime( get_template_directory() . $main_js_filename ), true );
wp_enqueue_script( 'main-script' );

And that’s it. Now, you can reload the page as normal to see the implementation of your changes. 


  1. Pingback:Best way to clear static resources cache in WordPress – Engineering Sarokar

    1. Author

Leave a Reply

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