好的,下面是评论:
//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;
}
此时,对于新上传的图像,您将在Posteta表中获得所有信息
比率>1=水平
编辑了一些打字错误并完成了循环
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);