Created
February 1, 2012 20:54
-
-
Save thanosp/1719252 to your computer and use it in GitHub Desktop.
WP Theme Asset Versioning
This file contains hidden or 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 | |
/** | |
* Plugin Name: Theme Asset Versioning | |
*/ | |
/** | |
* Returns a versioned file name based on the last modified file date | |
* | |
* @param string $fileUrl Pointing to the file as would have been from the html | |
* @return string a versioned filename | |
*/ | |
function getAssetVersionNumber($wordpressFileUrl) | |
{ | |
$fileUrl = stripWordpressVersioning($wordpressFileUrl); | |
$fullPath = urlToFullPath($fileUrl); | |
$fileInfo = new SplFileInfo($fullPath); | |
if (!$fileInfo->isFile()) { | |
return $wordpressFileUrl; | |
} | |
$modTime = $fileInfo->getMTime(); | |
$extension = $fileInfo->getExtension(); | |
if (! $extension) { | |
return $wordpressFileUrl; | |
} | |
$versionedFilename = $fileInfo->getPath() . DIRECTORY_SEPARATOR . $fileInfo->getBasename('.'.$extension) . ".{$modTime}." . $extension; | |
return fullPathToUrl($versionedFilename); | |
} | |
add_filter('style_loader_src', 'getAssetVersionNumber'); | |
function stripWordpressVersioning($url) | |
{ | |
$url = preg_replace('/.css\?.*/', '.css', $url); | |
$url = preg_replace('/.js\?.*/', '.js', $url); | |
return $url; | |
} | |
function urlToFullPath($url) | |
{ | |
$path = str_replace(get_template_directory_uri(), get_template_directory(), $url); | |
return $path; | |
} | |
function fullPathToUrl($path) { | |
$url = str_replace(get_template_directory(), get_template_directory_uri(), $path); | |
return $url; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment