How To Remove Query Strings From Static Resources In WordPress

If you use popular website testing sites like Pingdom and GtMetrix, you will often times run across the following message:

Remove Query Strings From Static Resources –  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 warning comes with a very interesting recommendation. In layman’s terms, this means that some users will not be able to cache your static resources (images, css, js, etc) if they are using certain proxy servers. However, 99% of users will still be able to cache your resources, so this recommendation is not always “bad.”

The warning only improves the load time for a small subset of your potential user base. Query strings are not that bad. They allow you to bust users cache in the event of updates to provide a more reliable user experience when you change your website’s design.

How to Remove Query Strings

If you still want to remove query strings from your static resources, add the following piece of code to your functions.php file.

/**
* Remove query strings from static resources
*
* @version 1.0.0
* @since 1.0.0
* @return string Cleaned script URL
*/
function sert_script_version( $src ){
$parts = explode( '?ver', $src );
return $parts[0];
}
if ( ! is_admin() ) {
add_filter( 'script_loader_src', 'sert_script_version', 15, 1 );
add_filter( 'style_loader_src', 'sert_script_version', 15, 1 );
}

Important Note: This code will only apply to the front end of your website. The WP-Admin panel will still be served the query strings. (This prevents many issues involving WordPress and plugin updates.)

I recommend contacting a developer such as myself, for five minutes of my time, if you have questions about removing query strings.

scott hartley

About the author

Scott is a web performance geek, lover of all things coffee, and avid video game player. His WordPress work delves into web performance, web security, and SEO.

2 thoughts on “How To Remove Query Strings From Static Resources In WordPress”

    • Not quite the same snippet you find elsewhere this excludes the admin JS to avoid issues in future updates, with plugins like yoast who might not versions JS files / css files in the name. This snippet is slightly different.

      Additionally, many plugins might add junk to the admin panel whether it’s an extra menu option and instead want a simple snippet that doesn’t need updating. Sure I could modify the code to be broader but certain themes/plugins include query strings to differentiate files and other issues could arise.

      Reply

Leave a Comment