Created
February 11, 2022 12:46
-
-
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…
This file contains 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 | |
// 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