How to automatically version WordPress assets using their last modified time

Versioning your assets in WordPress is relatively straight-forward as the wp_register_script() and wp_register_style() functions both offer support for specifying a version as a function parameter.

It’s easy to use because you simply pass it a value but it’s also simple to forget which could result in site visitors loading up stale versions of CSS and JS from a cache.

Thankfully, PHP provides us with an easy method of ensuring the version parameter changes whenever the file changes.

<?php
add_action( 'wp_enqueue_scripts', function () {
$uri = get_stylesheet_directory_uri();
$dir = get_stylesheet_directory();
$script_last_updated_at = filemtime( "$dir/scripts/my-script.js" );
$style_last_updated_at = filemtime( "$dir/styles/my-style.css" );
wp_register_script( 'my-script', "$uri/scripts/my-script.js", [], $script_last_updated_at, true );
wp_register_style( 'my-style', "$uri/styles/my-style.css", [], $style_last_updated_at, true );
} );

Need a website? Let's talk.

From website design & SEO through to custom WordPress plugin development. I transform ideas into dynamic, engaging, and high-performing solutions.
Subscribe to get the latest insights & updates in the world of web and how it impacts your business and website.
© 2024 Phil Kurth  |  All rights reserved.