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
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);