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 () {

    wp_register_style(
        'my-styles',
        get_stylesheet_directory_uri() . '/styles.css',
        [],
        # the filemtime() returns function the time the file was last modified
        filemtime(get_stylesheet_directory() . '/styles.css')
    );

    wp_register_script(
        'my-script',
        get_stylesheet_directory_uri() . '/main.js',
        [],
        # the filemtime() function returns the time the file was last modified
        filemtime(get_stylesheet_directory() . '/main.js')
    );

    wp_enqueue_style('my-styles');
    wp_enqueue_script('my-script');
});
If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments