Get Exact Image

Only return an image that matches the exact dimensions of the image size. If the uploaded image is too small, making the cropped image incorrectly sized, use the fallback image ID instead.

/**
 * Get Exact Image
 * Only return image if matches image size dimensions
 *
 * @param int image_id
 * @param string image_size
 * @param int fallback_id
 * @param array $atr
 * @return string, image output
 */
function ea_get_exact_image( $image_id, $image_size, $fallback_id, $attr ) {
	// Gather image sizes
	global $_wp_additional_image_sizes;
	$sizes = array(
		'thumbnail' => array(
			'width'   => intval( get_option( 'thumbnail_size_w' ) ),
			'height'  => intval( get_option( 'thumbnail_size_h' ) ),
			'crop'    => 1,
		),
	);
	$sizes = array_merge( $sizes, $_wp_additional_image_sizes );
	// Remove non-cropping sizes
	foreach( $sizes as $name => $details ) {
		if( ! $details['crop'] ) {
			unset( $sizes[$name] );
		}
	}
	// If no image size but fallback defined, use that
	if( ! $image_id && $fallback_id )
		$image_id = $fallback_id;
	// If image size is non-cropping, return standard image
	if( ! array_key_exists( $image_size, $sizes ) )
		return wp_get_attachment_image( $image_id, $image_size, null, $attr );
	// See if image matches dimensions
	$img_details = wp_get_attachment_image_src( $image_id, $image_size );
	if( $img_details[1] == $sizes[$image_size]['width'] && $img_details[2] == $sizes[$image_size]['height'] ) {
		return wp_get_attachment_image( $image_id, $image_size, null, $attr );
	} elseif( $fallback_id ) {
		$img_details = wp_get_attachment_image_src( $fallback_id, $image_size );
		if( $img_details[1] == $sizes[$image_size]['width'] && $img_details[2] == $sizes[$image_size]['height'] ) {
			return wp_get_attachment_image( $fallback_id, $image_size, null, $attr );
		}
	}
	return false;
}

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk