-
-
Save rolandinsh/3021951 to your computer and use it in GitHub Desktop.
Filename-based cache busting for WordPress scripts/styles.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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