jcanfield
5/13/2011 - 8:28 PM

Improve WordPress cache busting to move the version into the URL path, instead of as a query variable

Improve WordPress cache busting to move the version into the URL path, instead of as a query variable

<?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();
}