wordpress Snippets 前端静态资源替换CDN地址

原地址: https://github.com/dannyvankooten/wp-cdn-loader

/*禁止直接访问*/
if( ! defined( 'ABSPATH' ) ) {exit;}
add_action( 'template_redirect', function() {
	if( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {return;}	
	$cdn_url = 'https://cdn.jsdelivr.net/gh/a-writer/Private/blog_v1';
	$site_url = get_home_url();

	$url_rewriter = new UrlRewriter( $cdn_url, $site_url );
	$url_rewriter->add_hooks();
});
class UrlRewriter {
	private $cdn_url = '';
	private $site_url = '';

	public function __construct( $cdn_url, $site_url ) {
		$this->site_url = $site_url;
		$this->cdn_url = $cdn_url;
	}
	public function add_hooks() {
		add_filter( 'theme_root_uri', array( $this, 'rewrite' ), 99, 1 );
		add_filter( 'plugins_url', array( $this, 'rewrite' ), 99, 1 );
		add_filter( 'script_loader_src', array( $this, 'rewrite' ), 99, 1 );
		add_filter( 'style_loader_src', array( $this, 'rewrite' ), 99, 1 );
		return true;
	}
	public function rewrite( $url ) {
		$url = str_replace( $this->site_url, $this->cdn_url, $url );
		return $url;
	}
}