Filter media library items by size

So far, the only workable solution I’ve come up with is to run a new query within the ajax_query_attachments_args filter.

It’s definitely not ideal but works as expected in the absence of a more efficient alternative:

function restrict_media_library_by_width($query) {
  $include = array();
  $exclude = array();
  $temp_query = new WP_Query($query);
  if($temp_query->have_posts()) {
    while($temp_query->have_posts()) {
      $temp_query->the_post();
      $meta = wp_get_attachment_metadata(get_the_ID());
      $meta['mime-type'] = get_post_mime_type(get_the_ID());
      if(isset($meta['mime-type']) &&
        ($meta['mime-type'] == 'image/jpeg' && isset($meta['width']) && $meta['width'] >= 100) ||
         $meta['mime-type'] == 'image/svg+xml') {
        $include[] = get_the_ID();
      } else {
        $exclude[] = get_the_ID();
      }
    }
  }
  wp_reset_query();

  $query['post__in']     = $include;
  $query['post__not_in'] = $exclude;

  return $query;
}
add_filter('ajax_query_attachments_args', 'restrict_media_library_by_width');

Leave a Comment