WP-Mix

A fresh mix of code snippets and tutorials

WordPress Remove Query Strings from Scripts and Styles

I’ve had this post sitting here unpublished for a while now. Thought it’s finally time to post and share with anyone who may be looking for it. Basically here are two ways to remove query strings from the URLs of any registered scripts and styles. Let’s take a look..

Method 1

Here is the first (and recommended) way to strip any query string from script and style resources:

// remove version from scripts and styles
function shapeSpace_remove_version_scripts_styles ($src, $handle) {

	if (strpos($src, 'ver=')) {
		$src = remove_query_arg('ver', $src);
	}

	return $src;
}
add_filter('script_loader_src', 'shapeSpace_remove_version_scripts_styles', 10, 2);
add_filter('style_loader_src', 'shapeSpace_remove_version_scripts_styles', 10, 2);

Two keys to this simple script. First notice the two hooks that are used, style_loader_src and script_loader_src. These tap into the source URL for scripts and styles, respectively. Then secondly, notice the function used to remove the passed query string, remove_query_arg(). This is a core WordPress function that does the job of removing any query-string arguments as needed.

Method 2

The second way basically is the same, only using some vanilla PHP code instead of remove_query_arg() to do the actual removing of the query string. It looks like this:

// remove version from scripts and styles
function shapeSpace_remove_version_scripts_styles ($src, $handle) {

	$parts = explode('?', $src);

	return $parts[0];

}
add_filter('script_loader_src', 'shapeSpace_remove_version_scripts_styles', 10, 2);
add_filter('style_loader_src', 'shapeSpace_remove_version_scripts_styles', 10, 2);

This alternate method can be useful if further/specific handling of the various URL components is necessary. Otherwise, go with the first method is recommended.

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress