Is it possible to use WP_Query
to get attachment images by pixel size?
For example all images with a width of 500px and height of 300px. Or images with a height bigger than 300px.
As far as i can see i can catch this data in the meta query with 'key' => '_wp_attachment_metadata'
but what then? There seems no solution that is precise enough to target that width or height inside _wp_attachment_metadata
...
You cannot do it with wp_query as height and width do not have their own meta field (they are part of a serialized array). But this is easy enough to overcome, we can just assign them their own postmeta db entry when uploading (you can also use wp_query to get all images and loop over to update existing images)
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']);
return $meta;
}
You can then query for images greater than dimensions etc, something like this:
$types = array( 'image/jpeg', 'image/gif', 'image/png');
$args= array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => $types,
'meta_query' => array(
'relation' => 'AND', //-->this is default but showing here as you can use OR
array(
'key' => 'height',
'value' => 300,
'type' => 'numeric',
'compare' => '>',
),
array(
'key' => 'width',
'value' => 300,
'type' => 'numeric',
'compare' => '>',
),
)
);
$images= new WP_Query($args);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With