Coding Triumph

Helpful code snippets & tutorials

How to automatically version enqueued scripts and stylesheets in WordPress

WordPress loads assets using the URL query parameter “ver” (e.g., style.css?ver=5.01). This allows the browser and some WordPress plugins to cache these files for performance purposes.

This means that in order to load an updated version of CSS and JavaScript, you’ll have to either clear the cache or change your assets version. This can quickly become impediment during development when scripts are updated frequently.

In this article and with the help of the filemtime() function, I’ll show you how to automatically change the version of your assets whenever they are modified with a few lines of code. Here is the full script:

# this script will append a new version to your scripts when ever they are changed
add_action('wp_enqueue_scripts', function () {

        get_stylesheet_directory_uri() . '/styles.css',
        # the filemtime() returns function the time the file was last modified
        filemtime(get_stylesheet_directory() . '/styles.css')

        get_stylesheet_directory_uri() . '/main.js',
        # the filemtime() function returns the time the file was last modified
        filemtime(get_stylesheet_directory() . '/main.js')

If you like this post, please share
Notify of
Inline Feedbacks
View all comments