Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress : query by attachment meta (image size)

Tags:

wordpress

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 ...

like image 311
GDY Avatar asked Nov 08 '22 14:11

GDY


1 Answers

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);
like image 138
David Avatar answered Nov 15 '22 10:11

David