Last active
December 2, 2023 06:02
-
-
Save shazdeh/47b8b518cdf3a79d6705a3b6064ec0ca to your computer and use it in GitHub Desktop.
Find closest larger image size that matches $width and $height
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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