The Issue

If you have gone through WordPress generated source, you will generally see a query string at the end of you assets file be it CSS or JS. A typical example of the issue is a string attached at the end of the URL like so custom.min.css?ver=4.9.7 and this might be a problem when you are optimizing you site for better speed. When you check you site in tools like Pingdom or GTmatrix they suggest a removal of query string from the assets URL and it can be done easily in WordPress with this simple bit of code


// Remove query string from WordPress Assets
function smn_remove_script_version( $src ){
$parts = explode( '?', $src );
return $parts[0];
}
add_filter( 'script_loader_src', 'smn_remove_script_version', 15, 1 );
add_filter( 'style_loader_src', 'smn_remove_script_version', 15, 1 );

How to use this code?

Using this code is as simple as pasting it in your theme’s functions.php file. Caution: Make sure that you take a backup of your site before trying this code. Its always better to have a backup if something gets screwed up.

Your theme file is located inside wp-content/themes folder. You will find theme folder inside this location and functions.php file inside that.

How does it work?

We are creating a new function smn_remove_script_version and that function is converting URL string into Array by delimiter of ?. The first part is returned and the query part ?ver=4.7.9 is removed from the URL. Note that we have only written what to do but have not mentioned when and where to do it. For that we use WordPress’s most powerful feature called Hooks. We add a filter script_loader_src and all it does is removes the query string from all script (JS) files. Another filter we use is style_loader_src and it does exact same thing as previous one but this one removes version query string from CSS files.

If you are thinking what those number 15 and 1 is at the end, the number 15 signifies the priority of execution (default: 10). Lower number means high priority and early execution and second number 1 signifies the number of argument function accepts (default: 1).

Method Limitation

This method is limited to single theme only. If you change your theme this removal of query string might not be enabled by default. If you change your theme frequently, I recommend using Plugin to achieve the result.