WordPress – Dealing with lots of standard image sizes

May 16, 2012

WordPressWordPress is a fantastic tool for building websites but sometimes there are little things that are a bit tricky – one of those is thumbnail images. All the more frustrating because it gives you almost all of the tools you need – but not quite all of them. Here is a little utility function I have used to get around the fact that there is no wordpress function for getting a thumbnail image for a specific size (even when you have correctly generated the thumbnail at that size using the add_image_size function.

All this function does is accept an existing image URL and then switch out the current height and width (if present) and place in the specified height and width. So the procedure becomes simple – just use add_image_size to register your thumbnail sizes and then grab the image in your template as you normally would and use this function to get the URL of the thumbnail at the size you want. This is especially useful when you are using custom fields to insert images into your template, as you might not be sure if the user has selected the original, or a scaled version of the image.

Anyway, on to the code!

// utility for getting a thumbnail image from a different sized thumbnail image
// or the original. Assumes the size requested is auto generated
function oi_get_thumnail($existing_filename, $width, $height) {

  // do a clever regex replace
  return preg_replace('/(-\d+x\d+)?\.(\w{3,4})$/', '-'.$width.'x'.$height.'.\\2',$existing_filename);
}

And a [link off to a gist][2], if you are interested.

[2]: https://gist.github.com/2709106