Skip to content

Instantly share code, notes, and snippets.

@matysanchez
Last active October 14, 2019 19:49
Show Gist options
  • Save matysanchez/552534e06c4052c6ef67a6c8f4362ddb to your computer and use it in GitHub Desktop.
Save matysanchez/552534e06c4052c6ef67a6c8f4362ddb to your computer and use it in GitHub Desktop.
Easy way to add versioning to WordPress assets using the file timestamp as a version
<?php
// This function will add ?ver=XXXX at the end of the file
function AddTimestampToAssets( $assetURI ) {
// Get the FULL Relative URL
$relativeURL = getcwd() . '/' . ltrim( (str_replace( home_url(), '', $assetURI )), '/' );
// Check if the $relativeURL contains "?ver=", if so remove it
if ( strpos ($relativeURL, "?ver=") )
$relativeURL = explode("?ver=", $relativeURL)[0];
if ( $relativeURL ) {
// Get the timestamp using PHP native function
$timestamp = filemtime( $relativeURL );
// Add ?ver= parameter with value to the URI
$assetURI = add_query_arg( 'ver', $timestamp, $assetURI );
// Return the final URL
return esc_url( $assetURI );
}
}
// This function is going to add two WP filters to pass all the files to the AddTimestampToAssets function
function LoadAssetsWithVersioning() {
// CSS's
add_filter( 'style_loader_src', 'AddTimestampToAssets' );
// JS's
add_filter( 'script_loader_src', 'AddTimestampToAssets' );
}
// Let's force WP to run LoadAssetsWithVersioning when initialazing the site
add_action('init', 'LoadAssetsWithVersioning');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment