I was able to add the file last modified time as version to css and js files. As you can see I have to repeatly adding filemtime(get_theme_file_path('...')) every time when a new link is added.

function _enqueue_scripts() {
    wp_enqueue_style('_base', get_theme_file_uri('/assets/css/base.css'), array(), filemtime(get_theme_file_path('/assets/css/base.css')));
    wp_enqueue_script('_base', get_theme_file_uri('/assets/js/base.js'), array(), filemtime(get_theme_file_path('/assets/js/base.js')));
}
add_action('wp_enqueue_scripts', '_enqueue_scripts');

Is there a way to use a custom filter or so for it rather than manually add that line every time?

Similar to the below function (for removing version numbers), but I’d like to add version numbers.

function _remove_script_version($src) {
    return $src ? esc_url(remove_query_arg('ver', $src)) : false;
}
add_filter('style_loader_src', '_remove_script_version', 15, 1);
add_filter('script_loader_src', '_remove_script_version', 15, 1);

5 Answers
5

You could use add_query_arg() but then you’d have to parse the uri everytime, I’d rather create a wrapper function for wp_enqueue_script/style:

function my_enqueuer($my_handle, $relpath, $type="script", $my_deps=array()) {
    $uri = get_theme_file_uri($relpath);
    $vsn = filemtime(get_theme_file_path($relpath));
    if($type == 'script') wp_enqueue_script($my_handle, $uri, $my_deps, $vsn);
    else if($type == 'style') wp_enqueue_style($my_handle, $uri, $my_deps, $vsn);      
}

Add this in your functions file and then in place of e.g.

wp_enqueue_script('_base', get_theme_file_uri('/assets/js/base.js'), array(), filemtime(get_theme_file_path('/assets/js/base.js')));

call:

my_enqueuer('_base', '/assets/js/base.js');

and in place of e.g.

wp_enqueue_style('_base', get_theme_file_uri('/assets/css/base.css'), array(), filemtime(get_theme_file_path('/assets/css/base.css')));

call:

my_enqueuer('_base', '/assets/css/base.css', 'style');

You can pass the dependency array as the last argument when needed. For scripts, if you pass the dependency array, you will have to pass the third parameter ‘script’ as well, even though I’ve set it as the default value.

Leave a Reply

Your email address will not be published. Required fields are marked *