Skip to content

Instantly share code, notes, and snippets.

@dmhendricks
Last active November 13, 2022 10:56
Show Gist options
  • Save dmhendricks/fbf4c69b3c7a13ffa04526427083742a to your computer and use it in GitHub Desktop.
Save dmhendricks/fbf4c69b3c7a13ffa04526427083742a to your computer and use it in GitHub Desktop.
A simple WordPress plugin to remove the script version from linked CSS and JS scripts to improve cacheability.
<?php
/**
* @wordpress-plugin
* Plugin Name: Remove Script Versions
* Description: Removes the script version from linked CSS and JS scripts to improve cacheability.
* Plugin URI: https://gist.github.com/dmhendricks/fbf4c69b3c7a13ffa04526427083742a/
* Version: 1.0.0
* Author: Daniel M. Hendricks
* Author URI: https://daniel.hn/
* License: GPLv2 or later
*/
namespace CloudVerve;
defined( 'ABSPATH' ) || die();
final class Remove_Script_Versions {
private static $instance;
private static $all_scripts = false;
public static function init() {
if ( !isset( self::$instance ) && !( self::$instance instanceof Remove_Script_Versions ) ) {
self::$instance = new Remove_Script_Versions;
if( wp_doing_ajax() || wp_doing_cron() ) return self::$instance;
// To remove version from ALL linked scripts, add to wp-config.php: define( 'REMOVE_ALL_SCRIPT_VERSIONS', true );
self::$all_scripts = defined( 'REMOVE_ALL_SCRIPT_VERSIONS' ) && REMOVE_ALL_SCRIPT_VERSIONS;
// Remove script versions
add_action( 'style_loader_src', array( self::$instance, 'remove_script_versions' ), 9999 );
add_action( 'script_loader_src', array( self::$instance, 'remove_script_versions' ), 9999 );
}
return self::$instance;
}
/*
* Strips the ?ver= portion of file linked from wp-includes.
*
* @since 1.0.0
*/
public static function remove_script_versions( $src ) {
if( strpos( $src, 'ver=' ) && ( self::$all_scripts || strpos( $src, '/wp-includes' ) ) ) {
$src = remove_query_arg( 'ver', $src );
}
return $src;
}
}
Remove_Script_Versions::init();
@dmhendricks
Copy link
Author

Simply create a file named remove-script-versions.php inside your site's wp-content/plugins directory, copy-and-paste the above into it, save and activate the plugin in WordPress.

By default, it removes ?ver= from scripts and stylesheets located in wp-includes only. To remove the version from all links scripts and stylesheets, add the following to your wp-config.php file:

define( 'REMOVE_ALL_SCRIPT_VERSIONS', true );

If you use a caching proxy such as Cloudflare, you may need to purge your cache after upgrading WordPress or any plugins/themes in the future, to reflect changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment