Remove Query String From Stylesheets In WordPress

A website owner should always be trying to improve the speed of their website as much as possible. In WordPress there are many things you can do to help improve the performance of your website. Tips to improve the performance of your WordPress website When you run your website through speed tests such as Google Page Speed test one of the things they will flag up is the loading static content with query strings, such as stylesheets and JavaScript files. This is a problem as many proxies will not cache the resources if it has a querystring in the URL. A tip on the Google best practice pages is to remove all query strings from your static resources to enable proxy caching of the file. The problem with WordPress is whenever it includes a script or a stylesheet by using the wp_enqueue_style or wp_enqueue_script function it will include a querystring for the version of the file. Both of these functions have a version parameter which allows the developer to append any version number that they want to the querystring, if the version number doesn't exist in the function then WordPress will append the WordPress version to the end of the URLs.


wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
wp_enqueue_style( $handle, $src, $deps, $ver, $media );

When using these functions you can make sure that a version number is not added to URL by passing a NULL value on the version parameter. The reason why WordPress adds a version number to the end of the URLs is for updates, once WordPress is updated to a new version then this new version number will be added to the end of the URL. If any of the JavaScript or stylesheet files have changed in this update then the new version number will ensure that the browser fetches the latest version and not the version stored in the browser cache. There are a lot of scripts that are added to your website that you can not control, for example with any plugins that you have installed might add new stylesheet and javascript files to your website. You don't want to have to go through these wp_enqueue handles and remove them. The following code snippet will use a filter that will allow you to change the script URLs before they are output to the page. Removing these query strings will ensure that the proxy can cache these resources and therefore speeding up the loading time of your website.


function pu_remove_script_version( $src ){
    return remove_query_arg( 'ver', $src );
}

add_filter( 'script_loader_src', 'pu_remove_script_version' );
add_filter( 'style_loader_src', 'pu_remove_script_version' );

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring