Skip to content

Instantly share code, notes, and snippets.

@wooki
Created May 16, 2012 09:40
Show Gist options
  • Save wooki/2709106 to your computer and use it in GitHub Desktop.
Save wooki/2709106 to your computer and use it in GitHub Desktop.
Wordpress function to get a thumbnail image filename from a different sized thumbnail or the the source
// utility for getting a thumbnail image from a different sized thumbnail image
// or the original. Assumes the size requested is auto generated
// eg. ..../2012/05/TSStAlbans-h1091-1024x750.jpg
// to../2012/05/TSStAlbans-h1091-300x200.jpg
//
// Or. ..../2012/05/TSStAlbans-h1091.jpg (source image)
// to../2012/05/TSStAlbans-h1091-300x200.jpg
//
// Add standard image sizes using add_image_size function and rebuild
// thumbnails when needed using AJAX Thumbnail Rebuild plugin.
//
// See:
// http://codex.wordpress.org/Function_Reference/add_image_size
// http://wordpress.org/extend/plugins/ajax-thumbnail-rebuild/
function jimcode_get_thumnail($existing_filename, $width, $height) {
// do a clever regex replace
$filename = preg_replace('/(-\d+x\d+)?\.(\w{3,4})$/', '-'.$width.'x'.$height.'.\\2',$existing_filename);
if ($filename == $existing_filename) {
// we didn't change anything - so check if we matched the same dimensions
if (preg_match('/-\d+x\d+\.(\w{3,4})$/', $existing_filename) == 0) {
$filename = preg_replace('/\.(\w{3,4})$/', '-'.$width.'x'.$height.'.\\1',$existing_filename);
}
}
// check if that actually exists and if not just return without any size
// get the url without the domain
$path = str_replace(get_option('home'), "", $filename);
$path = ABSPATH.$path;
$path = str_replace('/', DIRECTORY_SEPARATOR, $path);
$path = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);
if (file_exists($path)) {
return $filename;
} else {
return preg_replace('/(-\d+x\d+)?\.(\w{3,4})$/', '.\\2',$existing_filename);;
}
return $filename;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment