Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Filename-based cache busting for WordPress.
<?php
// changes CSS and JavaScript URLs from `css/style.css?ver=1.3.3.7` to `css/style.1.3.3.7.css`
if ( ! is_admin() ) {
foreach ( array( 'style_loader_src', 'script_loader_src' ) as $filter ) {
add_filter( $filter, function( $url ) {
// abort if `$url` doesn't start with `WP_CONTENT_URL`
if ( strpos( $url, WP_CONTENT_URL ) !== 0 )
return $url;
parse_str( parse_url( $url, PHP_URL_QUERY ) );
if ( isset( $ver ) ) {
$ver = preg_replace( '~[^.0-9]+~', '', $ver );
if ( strlen( $ver ) > 1 ) {
return preg_replace( '~(.+?)\.(css|js)~', "$1.$ver.$2", remove_query_arg( 'ver' , $url ) );
}
}
return $url;
});
}
}
# Redirect requests like `/css/style.1337.css` to `/css/style.css`.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)\.(\d+)\.(js|css)$ $1.$3 [L]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment