Create a gist now

Instantly share code, notes, and snippets.

WordPress Plugin: Filename-based cache busting for scripts/styles.
<?php
/**
* Plugin Name: Filename-based cache busting
* Version: 0.3
* Description: Filename-based cache busting for WordPress scripts/styles.
* Author: Dominik Schilling
* Author URI: http://wphelper.de/
* Plugin URI: https://dominikschilling.de/880/
*
* License: GPLv2 or later
* License URI: http://www.gnu.org/licenses/gpl-2.0.html
*
*
* Extend your .htaccess file with these lines:
*
* <IfModule mod_rewrite.c>
* RewriteEngine On
* RewriteBase /
*
* RewriteCond %{REQUEST_FILENAME} !-f
* RewriteCond %{REQUEST_FILENAME} !-d
* RewriteRule ^(.+)\.(.+)\.(js|css)$ $1.$3 [L]
* </IfModule>
*/
/**
* Moves the `ver` query string of the source into
* the filename. Doesn't change admin scripts/styles and sources
* with more than the `ver` arg.
*
* @param string $src The original source.
* @return string
*/
function ds_filename_based_cache_busting( $src ) {
// Don't touch admin scripts.
if ( is_admin() ) {
return $src;
}
$_src = $src;
if ( '//' === substr( $_src, 0, 2 ) ) {
$_src = 'http:' . $_src;
}
$_src = parse_url( $_src );
// Give up if malformed URL.
if ( false === $_src ) {
return $src;
}
// Check if it's a local URL.
$wp = parse_url( home_url() );
if ( isset( $_src['host'] ) && $_src['host'] !== $wp['host'] ) {
return $src;
}
return preg_replace(
'/\.(js|css)\?ver=(.+)$/',
'.$2.$1',
$src
);
}
add_filter( 'script_loader_src', 'ds_filename_based_cache_busting' );
add_filter( 'style_loader_src', 'ds_filename_based_cache_busting' );
@BenSampo

Thanks for this! Working perfectly.

@FStop

I don't know enough to know exactly why, but I had better luck omitting the

RewriteEngine On
RewriteBase /

lines in the .htaccess portion. I did notice that these lines were already present WordPress's .htaccess items.

Otherwise perfect & just what I was looking for. Thanks!

@jordantrizz

Has anyone tested this with Wordpress 4.x?

@Sophist-UK

just tested this on wp 4.1.1 and it doesn't work - urls still have ?ver=x.x at the end.

Anyone know how to make it work again?

@Sophist-UK

Looks like the add_filter does not have sufficient parameters. According to http://wpseek.com/hook/script_loader_src/ the function we define it needs a $handle parameter because apply_filter defines it - however I tried adding this and it made no difference.

@cdshepherd

Has anybody managed to get this working with Nginx? Specifically Nginx 1.4.6.
The plugin itself is changing the filenames, but I can't get Nginx to load the files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment