Display one random image, but only if landscape

I want to pull one random image and use it as a background image —- but ONLY if it’s a landscape image.

I found this post:

https://stackoverflow.com/questions/37537577/wordpress-query-by-attachment-meta-image-size

which is a pretty good explanation of how to start here.

For my purposes, landscape can be as simple as width > height (any aspect ratio greater than 1).

But I’m not totally sure how to add that as part of the metadata and then query for it (based on the above answer.)

Thanks.

1 Answer
1

ok, following the comments:

//from https://stackoverflow.com/questions/37537577/wordpress-query-by-attachment-meta-image-size

add_filter('wp_generate_attachment_metadata', 'add_metac', 10, 2);


function add_metac($meta, $id){

update_post_meta($id, 'height', (int) $meta['height']);
update_post_meta($id, 'width', (int) $meta['width']);
update_post_meta($id, 'ratio', round ($meta['width']  / $meta['height'] , 2 ));
return $meta;

}

at this point you will have, for the newly uploaded images, in the postmeta table all the information
enter image description here
and a ratio >1 = horizontal

EDITED some typo and completed with loop

function stack_309636_get_horizontal_bg( $width=900 , $ratio=1 ){
  $types = array( 'image/jpeg', 'image/gif', 'image/png');
  $args= array(
    'post_type'         => 'attachment',
    'post_status'    => 'inherit',
    'posts_per_page' =>   1,
    'orderby'      =>'rand',
    'post_mime_type'    => $types,
    'meta_query' => array(
        'relation' => 'AND', 
        array(
                'key'     => 'width',
                'value'   => $width, //the minimum required
                //'type'    => 'numeric',
                'compare' => '>',
        ),
        array(
                'key'     => 'ratio',
                'value'   => $ratio,  //eventually 1.5 or higher
                //'type'    => 'numeric',
                'compare' => '>',
        ),
    )

  );

  $query= new WP_Query($args);

  if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        $img = wp_get_attachment_image_src( $query->post->ID,'full');                            
        $return=$img[0];
        break;
      }
  }
  else 
    $return="your_default_image_url"; // in case no images match 
  wp_reset_query();

  return $return;
}

echo stack_309636_get_horizontal_bg(1200, 1.5);

Leave a Comment