Image Sizes

When you upload a picture to your WordPress website, images with additional sizes will be created. Why do we need them? Because we don’t use the image with the only one resolution everywhere on the site: in posts, in portfolio, in popups, as post thumbnails, in widgets, in administration area; There are a lot of […]

  /  April 6, 2015  /   9

When you upload a picture to your WordPress website, images with additional sizes will be created. Why do we need them? Because we don’t use the image with the only one resolution everywhere on the site:

  • in posts,
  • in portfolio,
  • in popups,
  • as post thumbnails,
  • in widgets,
  • in administration area;

There are a lot of different places on the website where you can use the same image. Sure, the images should be in different resolutions too.

But do not create a lot of image sizes as well:

  • the more image sizes you create — the more files will be in your uploads folder,
  • and the more time will need to upload an image to your site.

Default WordPress Image Sizes

WordPress supports several image sizes by default. You can find and change them in administration area in «Settings > Media».

Default image sizes in WordPress

What if you don’t use them and do not want WordPress to generate a copy for each of these sizes. You can insert the following hook into your theme functions.php:

function rudr_unset_image_sizes( $def_sizes) {
	unset( $def_sizes['thumbnail']); // turn off thumbnail size
	unset( $def_sizes['medium']); // turn off medium size
	unset( $def_sizes['large']); // turn off large size
	return $def_sizes;
}
 
add_filter('intermediate_image_sizes', 'rudr_unset_image_sizes');

How to Use Image Sizes on the Website

In Administration Area

Easy enough — just choose the image size you need when inserting an image into a post:

Image sizes dropdown in WP media uploader

In Code

There are a lot of functions to work with images in WordPress. When I need to print image on the page I usually use get_the_post_thumbnail(), the_post_thumbnail() or wp_get_attachment_image_src().

Most of them has the special paremeter to specify the image size, i.e:

the_post_thumbnail('large');

How to Add your Own Image Size

This process is very simple and consists of two steps. The first step is required.

Step 1. add_image_size()

Open your functions.php and insert:

add_image_size( 'my-image-size-name', 244, 344, true );

add_image_size() function has four paremeters:

my-image-size-name
Image size name
244
Width in pixels.
344
Height in pixels.
true
Hard (true) or soft (false) proportional mode.

Step 2. How to Add your Custom Image Size into Media Uploader

As I told your before, this is the unnecessary step. But in latest versions of WordPress (3.5+) this is very easy to do, so, you can just add this code to your functions.php:

add_filter('image_size_names_choose', 'rudr_new_image_sizes');
 
function rudr_new_image_sizes($sizes) {
	$addsizes = array(
		"my-image-size-name" => 'Misha size'
	);
	$newsizes = array_merge($sizes, $addsizes);
	return $newsizes;
}

The result:

custom image size in wordpress media uploader dropdown

How to Regenerate Images after Changing their Sizes or Changing a Theme

Perhaps you know a situation when after changing the parameters of add_image_size() or after changing your website theme the images with old resolutions are still displayed on the site.

What should you do in this situation? If there are only 2-3 pictures in your uploads folder, you can simply reupload them. But what to do if there are 2-3 thousands of images?

Ok, I can recommend you two simple plugins – Ajax Thumbnail Rebuild and Force Regenerate Thumbnail.

Get Rid of Unnecessary Image Sizes

So, let’s imagine that your website has 10 registered custom post types, and each of them use 2-3 image sizes on the website pages. It is easy to understand that when we upload any picture on the website WordPress creates 20-30 copies of it!

Here is a short code that solves this problem. This code tells WordPress when it needs to create the different resolution copy of the picture and when it doesn’t.

/*
 * this hook will be fired while you uploading a picture
 */
add_filter( 'intermediate_image_sizes', 'rudr_reduce_image_sizes' );
 
function rudr_reduce_image_sizes( $sizes ){
	/*
	 * $sizes - all image sizes array Array ( [0] => thumbnail [1] => medium [2] => large [3] => post-thumbnail )
	 * get_post_type() to get post type
	 */
	$type = get_post_type($_REQUEST['post_id']); // $_REQUEST['post_id'] post id the image uploads to
 
	foreach( $sizes as $key => $value ){
 
		/*
		 * use switch if there are a lot of post types
		 */
		if( $type == 'page' ) {
			if( $value == 'regionfeatured' ){ // turn off 'regionfeatured' for pages
    				unset( $sizes[$key] );
    			}
		} else if ( $type == 'region' ) {
			if( !in_array( $value, array('regionfeatured','misha335') ) ){ // for regions turn off everyting except 'regionfeatured' and 'misha335'
    				unset( $sizes[$key] );
    			}
		} else {
			if( $value != 'thumbnail' ){ // turn off everything except thumbnail
    				unset( $sizes[$key] );
    			}
		}
	}
	return $sizes;
}

Only the best of WordPress

once a week, no spam

Comments 9

  • Hello,
    thanks for sharing, but can you be more specific with the last example?
    At the moment I have a problem with a theme with several custom post types and several custom sizes for each image, with total of 20 images, which creates a total waste

    • Hello,
      please, tell me the image size names for each post type and each taxonomy. I can help you with the code then.

      • Hi,
        after a little bit thinking, I have found how does it work and really solved most of the problem.
        I have standart posts with galleries, which are posted from admin backend and for them I can limit the image sizes. This is the biger part of the problem, because standart posts are with galleries with 15 – 20 images /15 * 20 custom image size are 300images for only one post/.
        Smaller part of the problem is that custom post types are published from frontend and for them I can’t apply the code above.
        At the moment image sizes are generated on upload, Is it possible to generate only sertain size of the image, only on request for that size?

        • Hi,

          Smaller part of the problem is that custom post types are published from frontend and for them I can’t apply the code above.

          Try to apply save_post filter or another.

          At the moment image sizes are generated on upload, Is it possible to generate only sertain size of the image, only on request for that size?

          I’m not sure how this can be implemented.

  • Sallie GoetschDecember 14, 2016 at 03:12

    This looks like pretty much exactly what I need, but I was wondering about the hook. Why does this go on intermediate_image_sizes() and not on intermediate_image_sizes_advanced()? I’ve seen a couple of different suggested solutions for this problem and don’t know why some use one hook and some the other.

    • Hi Sallie,

      good question. And let me give you a good answer :)

      intermediate_image_sizes

      This filter hook applies before intermediate_image_sizes_advanced and passes only one parameter — the array of image sizes names, for example: array('thumbnail', 'medium', 'large', 'custom_size').

      So we can unset any of image sizes on the early step:

      add_filter('intermediate_image_sizes', 'early_image_sizes_unset', 10, 1 ); 
      function early_image_sizes_unset( $image_sizes_names ) {
      	unset( $image_sizes_names['large'] );
      }

      If you unset image sizes in intermediate_image_sizes (but not in intermediate_image_sizes_advanced), it could improve website performance for a little because it prevents some actions in the code, I suppose.

      intermediate_image_sizes_advanced

      This filter runs after the image sizes names are converted into an associative array. You can use this filter the same way to unset image sizes by name, but you can use additional values that are passed to the filter.

      add_filter('intermediate_image_sizes_advanced', 'late_image_sizes_unset', 10, 2 ); 
      function late_image_sizes_unset( $sizes, $metadata ) {
      	// $sizes = array( 'thumbnail' => array( 'width' => 'SIZE WIDTH', 'height' => 'SIZE HEIGHT', 'crop' => 'SIZE CROPPING' ),  ...... )
      	// $metadata = array( 'width' => 'ORIGINAL FILE WIDTH', 'height' => 'ORIGINAL FILE HEIGHT', 'file' => 'FILE PATH' )
      	// so we could try to add a condition
      	if( $metadata[ 'width' ] < 500 && $metadata[ 'width' ] < 400 )
      		unset( $sizes['medium'] );
      }
      • Sallie GoetschDecember 14, 2016 at 20:12

        Thanks so much for the detailed explanation. I noticed when I added your code to my `functions.php` file, I got a “headers already sent” error in my Debug Bar.

  • Jeremy CarlsonJanuary 31, 2017 at 20:01

    Misha, this is brilliant! Thank you so much.

    In my case, I was uploading small graphics that are already the right size — ads and logos which have been prepped elsewhere. For that case, I wrote:

    if( $type == 'sponsor' || $type == 'button' ) {
      if( $value != 'full' ){ // skip all sizes for sponsors and buttons - these will be small images anyway
        unset( $sizes[$key] );
      }
    }

Leave your question or feedback

phpjsHTMLCSSSQLCode
Please, enter a comment
Please, enter a name
Incorrect email