Is it possible to pull and display a single landscape oriented image

I wanted to know if this is possible. I have gone through a lot of threads on the internet for this one and there does not seem to be one good solution. I run a business website based on wordpress and now there is this peculiar requirement wherein I need a hack/code to pull and display one single image ( from among the other images uploaded/attached to that post ).

Now the tricky part is that the image must be a horizontally/landscape oriented image only. And if it does not find a landscape image it may return nothing. Please let me know if need more clarifications.

Read More

If you must know, I already have a featured image.

Related posts

Leave a Reply

1 comment

  1. 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