Last active
November 13, 2022 10:56
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simply create a file named
remove-script-versions.php
inside your site'swp-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 inwp-includes
only. To remove the version from all links scripts and stylesheets, add the following to yourwp-config.php
file: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.