Created
February 20, 2021 15:26
-
-
Save isotrope/0f23d5a08e11d75a0c4affd9c771a8ff to your computer and use it in GitHub Desktop.
How to add a query var based on the asset's file mod time.
This file contains hidden or 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 | |
/* | |
* These two techniques add a query var with the modified filetime of the CSS file | |
* | |
* It works great for cache-busting at the browser level | |
* It won't help with Cloudflare cache. That one needs to be purged as even with the query var, | |
* it will decide to send the old file contents. | |
* | |
* Of course, if you're using a cache plugin and tell it to discard the query vars, | |
* this process becomes moot. (or, as Joey Tribbiani would say, "it becomes moo") | |
* | |
* | |
* One thing to look for is the assets request's headers. | |
* Open your browser's dev tools and head to the Network tab. | |
* Here, you can filter the calls for JS files or CSS files only. | |
* Look for the file you're trying to update. Click on it and check its headers. | |
* Chances are that you will see an older "modified date" than what you would like it to use. | |
* ...time to PUUUUURGE!!! | |
* * | |
*/ | |
add_action( 'wp_enqueue_scripts', 'iso_enqueue_plugin_assets' ); | |
function iso_enqueue_plugin_assets() { | |
// will grab something like 2021-02-20_10-20-00 | |
$css_time = date_i18n( "Y-m-d_H-i-s", filemtime( plugin_dir_path( __FILE__ ) . 'assets/dist/css/my-plugin-styles.css' ) ); | |
// the version argument will add a query var "v" | |
// result = https://my-site.com/wp-content/plugins/my-plugin/assets/dist/css/my-plugin-styles.css?v=2021-02-20_10-20-00 | |
wp_enqueue_style( 'my-styles', plugin_dir_url( __FILE__ ) . 'assets/dist/css/my-plugin-styles.css', [ /* dependancies */ ], $css_time ); | |
} | |
add_action( 'wp_enqueue_scripts', 'iso_enqueue_theme_assets' ); | |
function iso_enqueue_theme_assets() { | |
// will grab something like 2021-02-20_10-20-00 | |
$css_time = date_i18n( "Y-m-d_H-i-s", filemtime( get_stylesheet_directory() . 'assets/dist/css/my-theme-styles.css' ) ); | |
// result = https://my-site.com/wp-content/themes/my-theme/assets/dist/css/my-plugin-styles.css?v=2021-02-20_10-20-00 | |
wp_enqueue_style( 'my-styles', get_stylesheet_directory_uri() . 'assets/dist/css/my-theme-styles.css', [ /* dependancies */ ], $css_time ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment