Friday, July 31, 2015

Managing image size with wordpress

If we display an image at a size of 450×300 pixels, then having an image file of roughly the same size is a good idea. If the source file is 2250×1500 pixels, the image will show up just fine, but instead of loading a 50 KB image, we would be loading a 500 KB image, while achieving the same effect.

WordPress is super-smart, though, taking care of this for us by churning out different sizes for each image we upload. See the dimensions it creates by going to the media settings in the back end. We can modify these once we have the final layout.
For an image-centric website, we might want to add a couple of more sizes, to make sure we never serve an image that is bigger than needed. By putting the following code in our theme’s functions.php file, we create two extra sizes:
add_image_size( 'large_thumb', 75, 75, true );
add_image_size( 'wider_image', 200, 150 );
The first line defines an image that is cropped to exactly 75×75 pixels, and the second line defines an image whose maximum dimension is 200×150, while maintaining the aspect ratio. Note the name given in the first argument of the function, because we will be referring to it when retrieving the images, which we can do like so:
wp_get_attachment_image_src( 325, 'wider_image');
The first argument is the ID of the attachment that we want to show. The second argument is the size of the image.

No comments:

Post a Comment