WordPress:按附件元查询(图像大小)

GDY*_*GDY 5 wordpress

是否可以使用WP_Query按像素大小获取附件图像?

例如,所有图像的宽度为500像素,高度为300像素.或高度大于300像素的图像.

据我所知,我可以在元查询中捕获这些数据,'key' => '_wp_attachment_metadata'但是呢?似乎没有足够精确的解决方案来定位内部的宽度或高度_wp_attachment_metadata......

Dav*_*vid 2

您无法使用 wp_query 执行此操作,因为高度和宽度没有自己的元字段(它们是序列化数组的一部分)。但这很容易克服,我们可以在上传时为它们分配自己的 postmeta 数据库条目(您也可以使用 wp_query 获取所有图像并循环更新现有图像)

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;

}
Run Code Online (Sandbox Code Playgroud)

然后,您可以查询大于尺寸等的图像,如下所示:

$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);
Run Code Online (Sandbox Code Playgroud)