Register script/style: Is it possible to customize the version query string via plugin?

Expanding on the question in the title:

I would like to find a way (via a plugin) to use timestamps for the JS and CSS file version query strings that are output with wp_register_style and wp_register_script.

Read More

I know this can be easily modified in the calls themselves, and I do it this way currently:

$style_mtime = filemtime(dirname(__FILE__) . '/css/style.css');
wp_register_style( 'fstop-stylesheet', get_stylesheet_directory_uri() . '/library/css/style.css', array(), $style_mtime , 'all');
wp_enqueue_style( 'fstop-stylesheet' );

I would love it if I could pass the timestamp portion off into a plugin. I recently found this plugin that does a good job of moving the query string into the filename, which should result in better caching for proxies:
https://gist.github.com/ocean90/1966227

And it does work well. I would like to add the timestamp bit in to automate the whole process.

Ideas?

Related posts

Leave a Reply

1 comment

  1. Old answer (based on misconception that you wanted a cache buster): You can use add_query_arg() which adds/replaces query arguments.

    <?php
    /**
    * Plugin Name: wpse_84670
    * Version: 0.0.1
    * Description: replace script/style version with time as a cache buster
    */
    
    /**
    * replace script or stylesheet version with current time
    * @param  string $url the source URL
    * @return string
    */
    function wpse_84670_time_as_version($url) {
        return add_query_arg(array('ver' => time()), $url);
    }
    
    add_filter('script_loader_src', 'wpse_84670_time_as_version');
    add_filter('style_loader_src', 'wpse_84670_time_as_version');
    

    New answer: don’t do that! It will force a file access for every enqueued script and stylesheet on a page, and depending on what plugins you have activated that could mean an additional dozen or more file accesses for every access to a page/post. Many of them won’t even result in the browser requesting those files (if you have expired times configured for scripts and stylesheets — and you should!)

    Instead, just wrap a function around your enqueuing code for your theme, so that you only make a file access for the files your theme enqueues.

    Better still, keep a rolling version number in your theme (in my themes, I call it $forceLoad) and use that as the version passed to wp_enqueue_script. No additional file access required.

    $forceLoad = '42';
    wp_enqueue_style('fstop-stylesheet', get_stylesheet_directory_uri() . '/library/css/style.css', false, $forceLoad, 'all');