Function to retrieve “landscape” oriented image
function wpse_96012_landscape_image() {
/* global post object holding info about the current post */
global $post;
/* grab all images attached to the current post */
$attached_images = get_children( array(
'post_parent' => $post->ID,
'post_type' => 'attachment',
'post_mime_type' => 'image'
) );
/* set minimum ratio between width / height, change to your liking */
$minimum_aspect_ratio = 1.2;
/*
* iterate over attachments
* get size, compare width & height
* stop execution if an image with "landscape" dimensions is found
*/
foreach( $attached_images as $image ) {
$url = wp_get_attachment_url( $image->ID );
$size = getimagesize( $url );
if ( $size[0] >= ( $size[1] * $minimum_aspect_ratio ) ) {
return $url;
}
}
return false;
}
Later Usage
The above function will return the URL of the first image with an aspect ratio higher than or equal to the set minimum or false
if none was found.
Hence, if you’d like to output the image on the condition of there being one, this is how you’d go about it:
$landscape_image_url = wpse_96012_landscape_image();
if ( $landscape_image_url ) {
echo '<img alt="landscape image" src="' . $landscape_image_url . '" />';
}
References
get_children
(WP)getimagesize
(PHP)