Skip to content

Instantly share code, notes, and snippets.

@kingkool68
Last active March 25, 2019 08:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingkool68/72a97581809f1dcf10dbda90739694a8 to your computer and use it in GitHub Desktop.
Save kingkool68/72a97581809f1dcf10dbda90739694a8 to your computer and use it in GitHub Desktop.
Replace the `ver` query arg with the file's last modified timestamp (WordPress CSS/JS Cache Busting)
<?php
/**
* Replace the `ver` query arg with the file's last modified timestamp
*
* @param string $src URL to a file
* @return string Modified URL to a file
*/
function filter_cache_busting_file_src( $src = '' ) {
global $wp_scripts;
// If $wp_scripts hasn't been initialized then bail.
if ( ! $wp_scripts instanceof WP_Scripts ) {
return $src;
}
// Check if script lives on this domain. Can't rewrite external scripts, they won't work.
$base_url = apply_filters( 'cache_busting_path_base_url', $wp_scripts->base_url, $src );
if ( ! strstr( $src, $base_url ) ) {
return $src;
}
// Remove the 'ver' query var: ?ver=0.1
$src = remove_query_arg( 'ver', $src );
$regex = '/' . preg_quote( $base_url, '/' ) . '/';
$path = preg_replace( $regex, '', $src );
$file = null;
// If the folder starts with wp- then we can figure out where it lives on the filesystem
if ( strstr( $path, '/wp-' ) ) {
$file = untrailingslashit( ABSPATH ) . $path;
}
if ( ! file_exists( $file ) ) {
return $src;
}
$time_format = apply_filters( 'cache_busting_path_time_format', 'Y-m-d_G-i' );
$modified_time = filemtime( $file );
$timezone_string = get_option( 'timezone_string' );
$dt = new DateTime( '@' . $modified_time );
$dt->setTimeZone( new DateTimeZone( $timezone_string ) );
$time = $dt->format( $time_format );
$src = add_query_arg( 'ver', $time, $src );
return $src;
}
add_filter( 'script_loader_src', 'filter_cache_busting_file_src' );
add_filter( 'style_loader_src', 'filter_cache_busting_file_src' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment