Cache-Busting Versions Based on File Changes
Replaces the version number on your theme's and plugins' CSS and JavaScript URLs with the file's last-modified time, so browsers and CDNs cache files for a long time but always fetch a fresh copy right after you change one.
Opens WPIDE on
Code
$wpide_mtime_version = function ( $src ) {
if ( ! is_string( $src ) || false !== strpos( $src, '/wp-includes/' ) || false !== strpos( $src, '/wp-admin/' ) ) {
return $src;
}
$content_url = set_url_scheme( content_url(), 'https' );
$clean = set_url_scheme( strtok( $src, '?' ), 'https' );
if ( 0 !== strpos( $clean, $content_url ) ) {
return $src;
}
$path = WP_CONTENT_DIR . substr( $clean, strlen( $content_url ) );
if ( false !== strpos( $path, '..' ) || ! is_file( $path ) ) {
return $src;
}
return add_query_arg( 'ver', (string) filemtime( $path ), $src );
};
add_filter( 'style_loader_src', $wpide_mtime_version, 15 );
add_filter( 'script_loader_src', $wpide_mtime_version, 15 );
Notes
File times are cached in memory for the request; WordPress core files keep their normal version.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.