Home / Admin / Automatic CSS/JavaScript Cache Busting
Duplicate Snippet

Embed Snippet on Your Site

Automatic CSS/JavaScript Cache Busting

Replace the `ver` query arg with the JavaScript/CSS file's last modified timestamp (WordPress CSS/JS Cache Busting)

Code Preview
php
<?php
    /**
	 * Replace the `ver` query arg with the file's last modified timestamp
	 *
	 * @param  string $src URL to a file
	 * @return string      Modified URL to a file
	 */
	function filter_cache_busting_file_src( $src = '' ) {
		global $wp_scripts;
		// If $wp_scripts hasn't been initialized then bail.
		if ( ! $wp_scripts instanceof WP_Scripts ) {
			return $src;
		}
		// Check if script lives on this domain. Can't rewrite external scripts, they won't work.
		$base_url = apply_filters( 'rh/cache_busting_path/base_url', $wp_scripts->base_url, $src );
		if ( ! strstr( $src, $base_url ) ) {
			return $src;
		}
		// Remove the 'ver' query var: ?ver=0.1
		$src   = remove_query_arg( 'ver', $src );
		$regex = '/' . preg_quote( $base_url, '/' ) . '/';
		$path  = preg_replace( $regex, '', $src );
		// If the folder starts with wp- then we can figure out where it lives on the filesystem
		$file = null;
		if ( strstr( $path, '/wp-' ) ) {
			$file = untrailingslashit( ABSPATH ) . $path;
		}
		if ( ! file_exists( $file ) ) {
			return $src;
		}
		$time_format     = apply_filters( 'rh/cache_busting_path/time_format', 'Y-m-d_G-i' );
		$modified_time   = filemtime( $file );
		$timezone_string = get_option( 'timezone_string' );
		if ( empty( $timezone_string ) ) {
			$timezone_string = 'Etc/GMT';
		}
		$dt = new DateTime( '@' . $modified_time );
		$dt->setTimeZone( new DateTimeZone( $timezone_string ) );
		$time = $dt->format( $time_format );
		$src  = add_query_arg( 'ver', $time, $src );
		return $src;
	}
add_filter( 'script_loader_src', 'filter_cache_busting_file_src' );
add_filter( 'style_loader_src', 'filter_cache_busting_file_src' );

Comments

Add a Comment