• Resolved southcast

    (@southcast)


    Hey guys,I wanted to know if this is possible. 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. Please let me know if need more clarifications.

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

Viewing 1 replies (of 1 total)
  • Thread Starter southcast

    (@southcast)

    Got the solution and it seems it is possible. I came back to this thread so that if someone else is looking to achieve something similar, they might find this helpful. Now the first piece of code has to go to your functions.php.

    function wpse_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;
    }

    Then there is this template tag you can use anywhere you want your image to be displayed.

    <?php $landscape_image_url = wpse_landscape_image();
    if ( $landscape_image_url ) {
        echo '<img alt="landscape image" src="' . $landscape_image_url . '" />';
    } ?>

    Also if you want to display vertical/portrait oriented image instead of landscape/horizontally oriented image then just change the indices in the code.

Viewing 1 replies (of 1 total)
  • The topic ‘Is it possible to pull and display a single landscape oriented image’ is closed to new replies.