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

时间:2016-05-31 05:37:53

标签: wordpress

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

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

据我所知,我可以使用'key' => '_wp_attachment_metadata'在元查询中捕获这些数据,但那么呢?似乎没有足够精确的解决方案来定位_wp_attachment_metadata ...

中的宽度或高度

2 个答案:

答案 0 :(得分:1)

你不能用wp_query来做,因为高度和宽度没有自己的元字段(它们是序列化数组的一部分)。但这很容易克服,我们可以在上传时为它们分配自己的postmeta db条目(你也可以使用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;

}

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

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

答案 1 :(得分:0)

@Dan被正确提到WP_Query和mysql无法处理这种方式。但是我们需要一个条件大小超过@ Dan的所有显示媒体的答案适合这个解决方案,但是当我们还需要分页参数和显示限制记录时,每个页面都有解决方案以下变更查询请求。

<?php

global $query_args;

$query_args = array(
    'post_type'      => 'attachment',
    'post_mime_type' => array('image/jpeg', 'image/gif', 'image/png'),
    'post_status'    => 'inherit',
    'fields' => 'ids'
);  // add pagination parameters in $query_args

add_filter( 'posts_request', function( $request ){

 global $wpdb, $query_args;

 remove_filter( 'posts_request', __FUNCTION__ );

 $all_media = $wpdb->get_results($request);

 if( empty( $all_media ) )
 return $request;

 $exclude_ids = array();

 foreach( $all_media as $media ){
     $meta = wp_get_attachment_metadata( $media->ID );
     if( $meta['width'] != 500 ||  $meta['height'] < 300 ) // Add condition also allow add more condition with different sizes
     $exclude_ids[] = $media->ID;
 }   

 if( $exclude_ids ){
   $query_args['post__not_in'] = $exclude_ids;
   $q = new WP_Query( $query_args );
   $request =  $q->request;
   wp_reset_query();      
 }

 return $request;  

});


$query = new WP_Query( $query_args );
//echo $query->request;
if( $query->have_posts() ){
  while( $query->have_posts() ){
      $query->the_post();
      echo get_the_title();
  }     

}

wp_reset_query();  

我没有测试更多记录。我希望这对你有帮助。