Showing other image sizes in the Media Gallery dialog

As I was developing the Really Simple Gallery Widget, I started defining more custom image sizes and was irritated to find that they didn’t show in the Media Gallery dialog, even though they were being generated. So, what’s a girl to do except fix that? I noticed that the Max Image Size Control plugin did add the sizes, so I looked inside the plugin to see how that was happening. Turns out there’s a not very well-known filter “attachment_fields_to_edit” which allowed me to do just what I needed to. Unfortunately, it doesn’t look too pretty because each of the items just floats to the left and they are not of consistent heights, but it works for what I need it to do. To use, just add the following to your functions.php or your plugin file.

/**
 * Add intermediate image sizes to media gallery modal dialog
 */

function image_sizes_attachment_fields_to_edit( $form_fields, $post ) {
	if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
		return $form_fields;

	if ( is_array($imagedata['sizes']) ) :
		foreach ( $imagedata['sizes'] as $size => $val ) :
			if ( $size != 'thumbnail' && $size != 'medium' && $size != 'large' ) :
				$css_id = "image-size-{$size}-{$post->ID}";
				$html .= '<div class="image-size-item"><input type="radio" name="attachments[' . $post->ID . '][image-size]" id="' . $css_id . '" value="' . $size . '" />';
				$html .= '<label for="' . $css_id . '">' . $size . '</label>';
				$html .= ' <label for="' . $css_id . '" class="help">' . sprintf( __("(%d&nbsp;&times;&nbsp;%d)"), $val['width'], $val['height'] ). '</label>';
				$html .= '</div>';
			endif;
		endforeach;
	endif;

	$form_fields['image-size']['html'] .= $html;
	return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'image_sizes_attachment_fields_to_edit', 100, 2 );

In action:

Intermediate sizes in the WordPress Media Gallery dialog

Resources: