I make a lot of WordPress themes, and frequently clients want to associate a particular size of image with a post. You can do this easily with WordPress by using
add_image_size() to define an image and then by calling
wp_get_attachment_image() later to print the markup for that image.
So for example, if I have an attachment image of ID number 123, I might do something like the following:
add_image_size( 'my-custom-size', 220, 180, true ); ... echo wp_get_attachment_image( 123, 'my-custom-size' );
add_image_size() defines the custom thumbnail (in this example the arguments tell
add_image_size() to make it 220 pixels wide, 180 high, and cropped), and
prints the markup of the image itself,
<img> element and everything.
This works great; WordPress even creates thumbnails in this size from now on. The problem is that it doesn’t apply to pre-existing thumbnails. And if people change their minds about what sizes they want their thumbnails to be (clients sometimes change their minds) you’re stuck with existing thumbnails of the wrong size.
In addition, if you call
wp_get_attachment_image( 123, 'my-custom-size' ); and that size doesn’t exist, WordPress just scales down the larger-sized original image, which might cause some performance issues.
Solution: Custom Image Sizes
My solution is the Custom Image Sizes plugin. You activate it, and if you call
wp_get_attachment_image() and related functions for an attachment that doesn’t have that size, WordPress will create it on demand.
As a bonus, if you pass a width and height of the desired image to
wp_get_attachment_image() (and related functions), you can create any size image. So for example I could create a thumbnail 50 pixels wide by 40 high of attachment 123 with the following code, where
echo wp_get_attachment_image( 123, '50x40' );