public
Last active

WordPress Plugin: Filename-based cache busting for scripts/styles.

  • Download Gist
fbcbfwss.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
<?php
/**
* Plugin Name: Filename-based cache busting
* Version: 0.2
* Description: Filename-based cache busting for WordPress scripts/styles.
* Author: Dominik Schilling
* Author URI: http://wphelper.de/
* Plugin URI: http://wpgrafie.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>
*/
/**
* Removes the `ver` query string of the source and places it 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;
 
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' );

Thanks for this! Working perfectly.

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!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.