Created
December 16, 2015 09:21
-
-
Save mattheu/439571b943bb6d86e840 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
/** | |
* | |
* Add file last modified time to version param of of enqueued scripts & styles | |
* | |
* This automagically busts cache whenever there is a change in a file. | |
*/ | |
add_action( 'wp_enqueue_scripts', function() { | |
global $wp_styles, $wp_scripts; | |
// Find path of site root. Accounts for WP in subdir. | |
$wp_dir = str_replace( home_url(), '', site_url() ); | |
$site_root_path = str_replace( $wp_dir, '', ABSPATH ); | |
foreach ( array( 'wp_styles', 'wp_scripts' ) as $resource ) { | |
foreach ( (array) $$resource->queue as $name ) { | |
if ( empty( $$resource->registered[$name] ) ) | |
continue; | |
$src = $$resource->registered[$name]->src; | |
// Admin scripts use path relative to site_url. | |
if ( 0 === strpos( $src , '/' ) ) | |
$src = site_url( $src ); | |
// Skip external scripts. | |
if ( false === strpos( $src, home_url() ) ) | |
continue; | |
$file = str_replace( home_url( '/' ), $site_root_path, $src ); | |
if ( ! file_exists( $file ) ) | |
continue; | |
$mtime = filectime( $file ); | |
$$resource->registered[$name]->ver = $$resource->registered[$name]->ver . '-' . $mtime; | |
} | |
} | |
}, 100 ); | |
add_filter( 'nocache_headers', function( $h ) { | |
if ( is_404() ) { | |
return array(); | |
} | |
return $h; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment