fbpx

An automatic versioning strategy for enqueued WordPress assets

WordPress makes enqueuing assets super simple and generally does its very best to keep those assets up to date where possible but we can take this a step further and use PHP’s filemtime() function to ensure our JavaScript and CSS files are given a new version whenever we make changes to them.

An example of automatic versioning when using wp_register_style() and wp_register_script()

By simply passing the asset’s full file path to filemtime() and using that in the $version parameter of either wp_register_style() or wp_register_script(), we can let PHP & WordPress manage the file’s version number and update the URI as we make changes to the files.

<?php
// A simple example of using filemtime() to version enqueued assets with their
// last modified time.
add_action( 'wp_enqueue_scripts', function () {
wp_register_style(
'styles',
get_stylesheet_directory_uri() . '/style.css',
[],
filemtime( get_stylesheet_directory() . '/style.css' )
);
wp_register_script(
'scripts',
get_stylesheet_directory_uri() . '/scripts.js',
[],
filemtime( get_stylesheet_directory() . '/scripts.js' )
);
wp_enqueue_style( 'styles' );
wp_enqueue_script( 'scripts' );
} );
view raw functions.php hosted with ❤ by GitHub

Note: wp_enqueue_style() and wp_enqueue_script() can also register assets for us directly

It is possible to skip the use of the wp_register_style() and wp_register_script() functions in the previous example and instead pass the additional arguments directly to the enqueue functions. Under the hood, the enqueue functions check for additional arguments and found, will register the asset before enqueuing.

<?php
// This example demonstrates how we can use wp_enqueue_style() and wp_enqueue_script()
// functions directly to both register and enqueue the asset in one call.
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_style(
'styles',
get_stylesheet_directory_uri() . '/style.css',
[],
filemtime( get_stylesheet_directory() . '/style.css' )
);
wp_enqueue_script(
'scripts',
get_stylesheet_directory_uri() . '/scripts.js',
[],
filemtime( get_stylesheet_directory() . '/scripts.js' )
);
} );

About the author

Phil Kurth is a web developer living in Melbourne, Australia. Phil has a long history of WordPress development and enjoys building tools to empower others in their web design/development practice.

When not working with the web, Phil is usually spending time with his two young sons or is out hiking through the Australian bush.

Good dev stuff, delivered.

Product news, tips, and other cool things we make.

We never share your data. Read our Privacy Policy

© 2021 Hookturn Digital. All rights reserved.