2

I want to implement cache busting on a specific script, but the version is not added to the url as query vars.

Here is the code I'm using :

wp_register_script( 'custom', get_stylesheet_directory_uri() . '/js/custom.min.js', array('jquery','modernizr'), filemtime( get_stylesheet_directory().'/js/custom.min.js' ), true );

I'm using the filemtime function to get the timestamp of the last modification as my version.

But in the source I get :

<script type='text/javascript' src='http://example.com/app/themes/MyTheme/js/custom.min.js'></script>

Where I would want something like http://example.com/app/themes/MyTheme/js/custom.min.js?v=1472031892

1
  • Try and check if this filemtime( get_stylesheet_directory().'/js/custom.min.js' ) is returning any value as it might return just false. Also try 'time()' instead and see if you get you desirable version Commented Aug 24, 2016 at 10:27

1 Answer 1

0

I can verify this is working for me and it looks much like the code you've provided.

Perhaps there is somewhere else you are defining your script. Can you give it a new handle name to check ('custom-xyz')?

Also, can you test the output of filemtime to see what it's outputting? I've added a "v" in front of it in case it returns false.

$ver = "v" . filemtime( get_stylesheet_directory().'/js/custom.min.js' );

wp_register_script( 'custom',

    get_stylesheet_directory_uri() . '/js/custom.min.js',

    array( 'jquery','modernizr' ),

    $ver,

    true);

wp_enqueue_script( 'custom' );

If, for the odd reason you can't get it to work correctly when you register, you could potentially filter the tag on output using script_loader_tag and some regex or str_replace.

wp_register_script( 'custom',

    get_stylesheet_directory_uri() . '/js/custom.min.js',

    array( 'jquery','modernizr' ),

    '%%CACHE_BUSTER%%',

    true);

wp_enqueue_script( 'custom' );

function script_tag_cache_buster( $tag, $handle, $src ) {

    if ( 'custom' === $handle ) {
        return str_replace( '%%CACHE_BUSTER%%', "v" . filemtime( get_stylesheet_directory().'/js/custom.min.js'), $tag );
    }

    return $tag;
}

add_filter( 'script_loader_tag', 'script_tag_cache_buster', 10, 3 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.