Skip to content

Instantly share code, notes, and snippets.

@rolandinsh
Forked from ocean90/fbcbfwss.php
Created June 30, 2012 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rolandinsh/3021951 to your computer and use it in GitHub Desktop.
Save rolandinsh/3021951 to your computer and use it in GitHub Desktop.
Filename-based cache busting for WordPress scripts/styles.
<?php
/**
* Filename-based cache busting for WordPress scripts/styles.
*
* 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>
*
* @param string $src The source with ?ver= suffix
* @return string
*/
function ds_filename_based_cache_busting( $src ) {
// Don't touch admin scripts.
if ( is_admin() )
return $src;
// Get the version string.
preg_match( '/\?ver=(.+)/', $src, $match );
$version = $match[1];
// No version detected, return the source.
if ( empty ( $version ) )
return $src;
// Remove version string from the source.
$src = preg_replace( '/\?ver=(.+)/', '', $src );
// Get the extension of the file, can be '.js' or '.css'.
$ext = '.' . pathinfo( $src, PATHINFO_EXTENSION );
// Build the new source.
$src = str_replace( $ext, '.' . $version . $ext, $src );
// Return the new source.
return $src;
}
add_filter( 'script_loader_src', 'ds_filename_based_cache_busting' );
add_filter( 'style_loader_src', 'ds_filename_based_cache_busting' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment