Add custom image sizes to your WordPress theme
By default, every time you upload an image in WordPress, it will create several cropped versions of the same image, for various uses across the site. For example, if you are showing a list of blog posts, you can display a very small thumbnail version of the Featured Image next to each post, which will load much faster than the full-size image. You can see the three default image sizes on the Settings > Media page: “Thumbnail”, “Medium” and “Large.” These are all good, but let’s say you have a custom layout that needs a new image size. That’s where the add_image_size() function comes in.
add_image_size()
According to the WordPress codex, the usage of the add_image_size function is as follows:
add_image_size( $name, $width, $height, $crop );
Using this as a guide, we can add a new custom image size to any theme by adding the following line to functions.php:
add_image_size('my-new-image-size-name', 600, 400, true);
This code will add a new image size, cropping at 600px wide by 400px high. Replace “my-new-image-size-name” with something to distinguish this image size from the default names already being used.
Using the New Image
To display the new image in your theme, use the following code inside the post loop:
echo get_the_post_thumbnail( $post->ID, 'my-new-image-size-name' );
Leave a Reply