For a long time, I manually changed the $version parameter when I was using wp_enqueue_script or wp_enqueue_style. At some point, I’d forget to make the change though and then some caching plugin would have issues because it wouldn’t realize that the script/style had been updated and I’d waste time wondering why I was seeing a cached version of scripts.
To combat this I started adding the version number of the plugin or theme as the $version
argument in wp_enqueue_script
so let’s look at how I do that.
get_file_data
My first stab at solving this problem was while writing a plugin and dealing with admin scripts and styles only. If this is your sole use case then get_plugin_data( __FILE__ )
will get you the information you need.
add_action( 'admin_enqueue_scripts', 'admin_enqueue' );
function admin_enqueue(){
$plugin_data = get_plugin_data( __FILE__ );
$version = $plugin_data['Version'];
wp_enqueue_script( 'my_script_name', plugins_url( '/plugin-folder/path-to/script.js' ), array( 'jquery'), esc_attr( $version ), true );
}
Unfortunately, if you want a method that works when you’re adding scripts to the frontend and to the admin area of WordPress you’re going to be let down by get_plugin_data
as this function is only defined in the WordPress admin area.
To get reliable access to this data anytime you want to add $version
to your enqueued scripts you need to use get_file_data
. This is available on both the frontend and the admin area in WordPress.
add_action( 'wp_enqueue_scripts', 'frontend_enqueue' );
function frontend_enqueue(){
$plugin_data = get_file_data( __FILE__, [
'Version' => 'Version',
], 'plugin' );
$version = $plugin_data['Version'];
wp_enqueue_script( 'my_script_name', plugins_url( '/plugin-folder/path-to/script.js' ), array( 'jquery'), esc_attr( $version ), true );
}
get_file_data
reads the first 8kb of a file for metadata embedded in the file. Then you can define the metadata values you want to be passed through in an array. The final declaration of plugin
above will translate into a filter that will be named extra_plugin_headers
that you could modify if needed.
Caveats
The biggest caveat to using get_file_contents
is that you need to be doing your enqueue work in the main plugin file that has the standard WordPress plugin headers as that is what the plugin is reading.
That works for me, and using get_file_contents
I can use a standard snippet to enqueue scripts and make sure I have the version number appended all the time.