John Wheal
John Wheal

Reputation: 10348

Wordpress add_image_size maximum height/width

I'm using the following Wordpress function to create a new image size:

add_image_size('image-custom', 500, 9999);

I have a rather unusual situation that I need to resize the image so that the maximum side (height or width) is 500px. Is this possible or do I need to create two image sizes and use logic when to display which image?

Upvotes: 2

Views: 5835

Answers (2)

Lumiere de Lune
Lumiere de Lune

Reputation: 141

When you set dimensions with the last parameter set to false, Wordpress does not crop the image, it resizes it proportionally within the limits set for width and height, which means that

add_image_size ( 'image-custom', 500 , 500 , false ) ;

will achieve exactly what you want : - landscape image will have a width of 500 and a height lower than 500, proportions kept - portrait images will have a height of 500 and a width lower than 500

Upvotes: 5

Marventus
Marventus

Reputation: 874

With CSS:

I would register one size only with large enough proportions so that it works for both landscape and portrait, and use max-height and max-width CSS properties:

.gallery img {
    max-height: 500px;
    max-width: 500px;
}

That way, the image will maintain its aspect ratio and adjust based on which dimension is larger: height or width.

With PHP (untested):

Assuming it's a WP gallery you are talking about:

/* In functions.php */
add_image_size('custom-portrait', 500, 9999, true);
add_image_size('custom-landscape', 9999, 500, true);

/* Inside the loop */
if ( get_post_gallery(get_the_ID(), false) ) {
    foreach( get_post_gallery(get_the_ID(), false)['ids'] as $id ) {
        $meta = wp_get_attachment_metadata( $id );
        echo $meta['height'] > $meta['width'] ? get_the_post_thumbnail('custom-portrait') : get_the_post_thumbnail('custom-landscape');
    }
}

Upvotes: 3

Related Questions