Skip to content

Instantly share code, notes, and snippets.

@isGabe
Created September 19, 2012 18:11
Show Gist options
  • Save isGabe/3751215 to your computer and use it in GitHub Desktop.
Save isGabe/3751215 to your computer and use it in GitHub Desktop.
WordPress: Auto versioning of CSS/JS files #snippet #WordPress
/*
Auto-version CSS & JS files, allowing for cache busting when these files are changed.
Place in functions.php or wherever you are enqueueing your scripts & styles
Avoids using query strings which prevent proxy caching
Adjust paths based on your theme setup. These paths work with Bones theme
*/
$mtime = filemtime(dirname(__FILE__) . '/css/style.css');
wp_register_style( 'bones-stylesheet', get_stylesheet_directory_uri() . '/library/css/style.' . $mtime . '.css', array(), null, 'all');
// enqueue the stylesheet
wp_enqueue_style( 'bones-stylesheet' );
/*
this will change css filename from style.css to style.1234567890.css, where 1234567890 is the time that the file was last saved.
IMPORTANT: Unless you use the .htaccess rewrite rule below (or something similar), this will break your site!
Feel free to throw things at me if this isn't done correctly. I took the idea from here:
http://w-shadow.com/blog/2012/07/30/automatic-versioning-of-css-js/
*/
# place this .htaccess file in your theme directory
# For now I cannot get this to work with WP Engine. It works fine locally (MAMP)
# Auto-versioning support
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]
</IfModule>
@mlebarron
Copy link

Forgot, you can't do the redirects in WPEngine's staging environment.

Anywhere I'm doing this I wrap it in

if(!strpos($_SERVER['SERVER_NAME'],'staging.wpengine.com'))

@eggbean
Copy link

eggbean commented Feb 8, 2014

The jQuery js on the WordPress sites I am trying to update already have versioning query strings, so would this affect that? I was only intending to add them to the theme style.css files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment