Created
May 13, 2011 20:28
-
-
Save sivel/971250 to your computer and use it in GitHub Desktop.
Improve WordPress cache busting to move the version into the URL path, instead of as a query variable
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 | |
/* | |
Plugin Name: Better Cache Bust | |
Plugin URI: http://sivel.net/ | |
Description: Moves the resource version in the URL path instead of as a query var | |
Version: 1.0 | |
Author: Matt Martz | |
Author URI: http://sivel.net/ | |
*/ | |
add_filter( 'script_loader_src', 'better_cache_bust', 5 ); | |
add_filter( 'style_loader_src', 'better_cache_bust', 5 ); | |
add_filter( 'stylesheet_uri', 'better_cache_bust', 5 ); | |
add_filter( 'stylesheet_directory_uri', 'better_cache_bust', 5 ); | |
function better_cache_bust( $src ) { | |
$site_url = home_url(); | |
if ( strpos( $src, $site_url ) !== 0 ) | |
return $src; | |
if ( strstr( $src, '/resource/ver' ) ) | |
return $src; | |
global $wp_version; | |
$query_string = parse_url( $src, PHP_URL_QUERY ); | |
parse_str( $query_string, $args ); | |
if ( in_array( current_filter(), array( 'stylesheet_uri', 'stylesheet_directory_uri' ) ) ) { | |
include_once(ABSPATH . '/wp-admin/includes/theme.php'); | |
$ct = current_theme_info(); | |
$args['ver'] = $ct->version; | |
} | |
if ( empty( $args['ver'] ) ) | |
$args['ver'] = $wp_version; | |
$src = $site_url . '/resource/ver/' . $args['ver'] . str_replace( array( $site_url, '?' . $query_string ), '', $src ); | |
unset( $args['ver'] ); | |
return add_query_arg( $args, $src ); | |
} | |
add_filter( 'mod_rewrite_rules', 'better_cache_bust_rewrites' ); | |
function better_cache_bust_rewrites( $rules ) { | |
$key_rule = 'RewriteRule ^index\.php$ - [L]'; | |
$new_rules = "$key_rule\n\nRewriteCond %{DOCUMENT_ROOT}/$2 -f\nRewriteRule ^resource/ver/([^/]+)/(.*)$ /$2 [L]\n"; | |
return str_replace( $key_rule, $new_rules, $rules ); | |
} | |
register_activation_hook( __FILE__, 'better_cache_bust_flush' ); | |
function better_cache_bust_flush() { | |
global $wp_rewrite; | |
$wp_rewrite->flush_rules(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For WordPress >= 3.4 replace
$ct = current_theme_info();
with$ct = wp_get_theme();
ascurrent_theme_info()
has been deprecated.