Skip to content

Instantly share code, notes, and snippets.

@shazdeh
Last active December 2, 2023 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shazdeh/47b8b518cdf3a79d6705a3b6064ec0ca to your computer and use it in GitHub Desktop.
Save shazdeh/47b8b518cdf3a79d6705a3b6064ec0ca to your computer and use it in GitHub Desktop.
Find closest larger image size that matches $width and $height
<?php
function find_nearest_image_size( $attachment_id, $width, $height ) : string {
$image_meta = wp_get_attachment_metadata( $attachment_id );
$size = '';
if ( ! empty( $image_meta['sizes'] ) ) {
$last_pixel_count = 0;
foreach ( $image_meta['sizes'] as $key => $value ) {
/* image size is smaller than what we need, skip */
if ( $width > $value['width'] || $height > $value['height'] ) {
continue;
}
/* find smallest size */
$pixels = $value['width'] * $value['height'];
if ( $last_pixel_count === 0 || $pixels < $last_pixel_count ) {
$last_pixel_count = $pixels;
$size = $key;
}
}
}
return $size;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment