Skip to content

Instantly share code, notes, and snippets.

@thanosp
Created February 1, 2012 20:54
Show Gist options
  • Save thanosp/1719252 to your computer and use it in GitHub Desktop.
Save thanosp/1719252 to your computer and use it in GitHub Desktop.
WP Theme Asset Versioning
<?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