If you are developing with WordPress, specially creating theme, browser needs to load your latest changes. Here is a trick to force your browser to reload the script or style:
A helper function:
[php]
/**
* Generates dynamic JS/CSS file version number for forcefully asset loading
*
* @param string $file file name relative to theme directory
* @return bool|int last file modification time
*/
function wedevs_asset_version( $file ) {
//file path will be relative to the current theme directory
$file_path = is_child_theme() ? STYLESHEETPATH : TEMPLATEPATH;
$file_path = $file_path . ‘/’ . $file;
if ( !is_readable( $file_path ) ) {
return;
}
return filemtime( $file_path );
}
[/php]
Here, we are getting the last file modification time of a file (js|css) from your current theme directory and returning the value. To use this helper function, you need to call the function with relative file path to your theme.
Usage:
[js]
wp_enqueue_script( ‘theme-script’, get_template_directory_uri() . ‘/js/scripts.js’, array(‘jquery’), wedevs_asset_version( ‘js/scripts.js’ ), true );
wp_enqueue_style( ‘custom-css’, get_template_directory_uri() . ‘/css/custom.css’, array(‘style’), wedevs_asset_version( ‘css/custom.css’ ) );
[/js]
Interesting way of handling it. I might have to check that out. Since I always try to bump the theme version when I make changes, I’ve been doing it based on theme version number like this:
$foo = wp_get_theme();
wp_enqueue_style( 'grid', get_stylesheet_directory_uri() . '/css/grid.css', array(), $foo['Version'], 'all' );
Hey Tareq,
I ran across another way to do this a while back and I thought about your post here.
I like this way better for some cases. Especially because I’ve seen some super aggressive caching where the browser even caches assets with a query string in the URL. I’ve seen several cases where Chrome does this and people were seeing old versions of a site for days.
This method does a rewrite that adds the last modified date to the filename that is returned and uses no query strings, ensuring things are cached and when updated they don’t stay cached when they’re not supposed to.
http://w-shadow.com/blog/2012/07/30/automatic-versioning-of-css-js/
Hola!
And why not using just “time()” for the version in the wp_enqueue_script?
wp_enqueue_script( ‘theme-script’, get_template_directory_uri() . ‘/js/scripts.js’, array(‘jquery’),time(), true );
That will work too, but it’ll force reload every time you visit the page.
Thanks for the tip