Skip to content

Instantly share code, notes, and snippets.

@BenSampo
Forked from ocean90/fbcbfwss.php
Created December 13, 2012 08:48
Show Gist options
  • Save BenSampo/4275057 to your computer and use it in GitHub Desktop.
Save BenSampo/4275057 to your computer and use it in GitHub Desktop.
<?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 e.g http://host.com/style.FILE_TIMESTAMP.css
*/
function filename_based_cache_busting($src) {
// Don't touch admin scripts.
if (is_admin()) {
return $src;
}
// Remove version string from the source.
$src = preg_replace('/\?ver=(.+)/', '', $src);
// Only for scripts on current domain
$domain = $_SERVER['HTTP_HOST'];
if (strpos($src, $domain) == false) {
return $src;
}
// Get the sources local file path
$src_local_path = str_replace(get_site_url(), ABSPATH, $src);
// Get the files last updated timestamp
$timestamp = filemtime($src_local_path);
// Get the extension of the file, can be '.js' or '.css'.
$ext = '.' . pathinfo($src, PATHINFO_EXTENSION);
// Build the new source.
$src = str_replace($ext, '.' . $timestamp . $ext, $src);
// Return the new source.
return $src;
}
add_filter('script_loader_src', 'filename_based_cache_busting');
add_filter('style_loader_src', 'filename_based_cache_busting');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment