Remove ?ver= from wp_register_script

The question:

I’m getting nags on google speed test regarding the querystrings in my scripts. So, I’m trying to remove them by passing false as the argument for that parameter. However, it does not seem to have effect:

wp_register_script('myscript', get_bloginfo('template_directory').'/scripts.myversionnumber.js',false,false,true);
wp_enqueue_script('myscript');

PS: the “myversionnumber” part of the js filename is my means of controlling cache/versioning rather than the ?ver= approach which apparently trips up some proxy servers (according to Google pagespeed test):

Remove query strings from static resources Enabling public caching in
the HTTP headers for static resources allows the browser to download
resources from a nearby proxy server rather than from a remote origin
server. Learn more

Suggestions for this page

Resources with a “?” in the URL are not cached by some proxy caching
servers. Remove the query string and encode the parameters into the
URL for the following resources:

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I think you have to pass NULL as the 4th parameter.

wp_register_script(
    'myscript',
    get_bloginfo('template_directory').'/scripts.myversionnumber.js',
    false,
    NULL,
    true);
wp_enqueue_script('myscript');

Method 2

You can pass null as the version value to wp_register_script or wp_enqueue_script and it should drop the query string.

<?php
wp_enqueue_script(
   'myscript',
   '/path/to/script.js',
   array(),
   null
);

Method 3

Foreword

I solved this a lot differently from SickHippie and chrisguitarguy and I guess it’s not the way it is supposed to be solved, but it’s working really good for me.

The code…

I put this snippet of code at the end of my theme’s functions.php file:

function remove_cssjs_querystring( $src ) {
  if( strpos( $src, '?rev=' ) ) // copy/paste this line and the next one to take away what you want from the end of your css/js
    $src = remove_query_arg( 'rev', $src );
  if( strpos( $src, 'ver=' ) )
    $src = remove_query_arg( 'ver', $src );
  return $src;
}
add_filter( 'style_loader_src', 'remove_cssjs_querystring', 10, 2 );
add_filter( 'script_loader_src', 'remove_cssjs_querystring', 10, 2 );

Where the idea came from…

I was loooking for it on Google and I found this article, but I kept having a problem with css/js: at this point my code still had (here and there) at the end something like .../some-stylesheet.css?rev=... and I thought about extending the code snippet a little bit to include anything that could have been after .css.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment