Skip to content

Instantly share code, notes, and snippets.

@walterebert
Last active December 5, 2016 11:29
Show Gist options
  • Save walterebert/acac86399facd9bf2acb to your computer and use it in GitHub Desktop.
Save walterebert/acac86399facd9bf2acb to your computer and use it in GitHub Desktop.
WordPress snippet: Add version to CSS/JS files automatically
<?php
function my_file_version( $file ) {
global $wp_version;
$version = $wp_version;
if ( file_exists( $file ) ) {
$version = filemtime( $file );
}
return (string) $version;
}
function my_version_js_css( $src ) {
$parts = explode( '?', $src );
$result = $parts[0];
if ( strpos( $result , home_url() ) !== false ) {
$result = preg_replace_callback( '#(.*?)((\.min)?\.(css|js))$#', function( $match ) {
$file = str_replace( home_url(), ABSPATH, $match[0] );
if ( file_exists( $file ) ) {
return $match[1] . $match[2] . '?v=' . my_file_version( $file );
} else {
return $match[0];
}
}, $result );
}
return $result;
}
add_filter( 'script_loader_src', 'my_version_js_css', 12, 1 );
add_filter( 'style_loader_src', 'my_version_js_css', 12, 1 );
add_filter( 'stylesheet_uri', 'my_version_js_css', 12, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment