Skip to content

Instantly share code, notes, and snippets.

@iansvo
Created February 11, 2022 12:46
Show Gist options
  • Save iansvo/9a7faa2c28b6af166ee76fbe0ccb0a73 to your computer and use it in GitHub Desktop.
Save iansvo/9a7faa2c28b6af166ee76fbe0ccb0a73 to your computer and use it in GitHub Desktop.
This is a simple pattern that uses a helper function to pass a dynamic version value to a style/script enqueue. This ensures WordPress updates the asset URL (e.g. the thing the browser downloads from) so it looks like its a new URL, and downloads the most recent version. This is all triggered when the file is modified on disk so its a simple way…
<?php
// This is used as a fallback if the file isn't found for some reason
global $wp_version;
/*
Note:
This function assumes you're only asking for files in your own theme
and that theme isn't a child theme. If you're using a child theme,
replace get_template_directory() with get_stylesheet_directory().
The file param is assumed to contain a leading forward slash, it
will fail if missing.
*/
function get_asset_version($file = null, $fallback = $wp_version) {
$path = get_template_directory() . $file;
return file_exists( $path ) ? filemetime($path) : $wp_version;
}
wp_enqueue_script(
'theme-js', // Handle
get_theme_file_uri('/dist/js/theme.min.js'), // web accessible URL to file
'', // Dependencies
get_asset_version('/dist/js/theme.min.js'), // Version - this will be a string representation of the modified timestamp
true // Include in footer
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment