Skip to content

Instantly share code, notes, and snippets.

@mdahlke
Created January 10, 2017 21:09
Show Gist options
  • Save mdahlke/fa9f38609882e72ad61a465c17482511 to your computer and use it in GitHub Desktop.
Save mdahlke/fa9f38609882e72ad61a465c17482511 to your computer and use it in GitHub Desktop.
Find the image that best fits a particular area of the page
<?php
$knownBestFits = [];
/**
* Find the smallest image to use in a given space with the minimal dimensions provided
* If width is the main decider, leave the height set at 0, and vice versa if the height is the main decider
* You may use both if a minimum height/width is needed
*
* @param $imageObj WP Image Object
* @param int $minWidth Minimum width the image needs to be
* @param int $minHeight Minimum height the image needs to be
*
* @return array
*/
function findBestFitImage($imageObj, $minWidth = 480, $minHeight = 0) {
$bestImage = array(
'id' => 0,
'title' => '',
'caption' => '',
'width' => 0,
'height' => 0,
'url' => '',
);
$imageSizes = $imageObj['sizes'];
$sizes = array('thumbnail', 'medium_large', 'large');
$size = 'original';
if ($imageSizes['thumbnail-width'] > $minWidth && $imageSizes['thumbnail-height'] > $minHeight) {
$size = 'thumbnail';
}
else if ($imageSizes['medium-width'] > $minWidth && $imageSizes['medium-height'] > $minHeight) {
$size = 'medium';
}
// for some reason some large images are small than medium_large images ???
else if ($imageSizes['large-width'] > $minWidth && $imageSizes['large-height'] > $minHeight &&
$imageSizes['large-width'] < $imageSizes['medium_large-width'] && $imageSizes['large-height'] < $imageSizes['medium_large-height']) {
$size = 'large';
}
else if ($imageSizes['medium_large-width'] > $minWidth && $imageSizes['medium_large-height'] > $minHeight) {
$size = 'medium_large';
}
if( $size === 'original' ){
return $imageObj;
}
$imgSize = $size . '-width';
$bestImage = array(
'id' => $imageObj['id'],
'title' => $imageObj['title'],
'caption' => $imageObj['caption'],
'width' => $imageObj['sizes'][$imgSize],
'height' => $imageObj['sizes'][$imgSize],
'url' => $imageObj['sizes'][$size],
);
return $bestImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment