按大小筛选介质库项目

时间:2015-03-07 作者:cfx

如果媒体库的宽度小于100px,我想阻止用户从媒体库中设置特色图像。原来我想用ajax_query_attachments_args 过滤器,但它会过滤WP_Query() 无法有效用于此目的的对象,因为meta_query\'smeta_key—这是_wp_attachment_metadata—包含序列化数据。这就是我目前正在尝试的:

function restrict_media_library_by_width($response, $attachment, $meta) {
  if(isset($response[\'width\']) && isset($response[\'height\']) && $response[\'width\'] >= 100) {
    return $response;
  }
  return false;
}
add_filter(\'wp_prepare_attachment_for_js\', \'restrict_media_library_by_width\', 10, 3);
我看到的结果是,媒体库模式弹出,加载一个“空”缩略图,AJAX加载程序继续断断续续地出现和消失:

enter image description here

但是,如果我将if语句中的最后一个条件更改为使用== 而不是>= 然后,它似乎像预期的那样工作for certain values:

function restrict_media_library_by_width($response, $attachment, $meta) {
  if(isset($response[\'width\']) && isset($response[\'height\']) && $response[\'width\'] == 100) {
    return $response;
  }
  return false;
}
add_filter(\'wp_prepare_attachment_for_js\', \'restrict_media_library_by_width\', 10, 3);
这并不总是奏效,但我怀疑我在这里遗漏了什么。有人能解释一下吗?谢谢

1 个回复
SO网友:cfx

到目前为止,我提出的唯一可行的解决方案是在ajax_query_attachments_args 滤器

这肯定不理想,但在没有更有效的替代方案的情况下,它的效果与预期一样:

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\');

结束

相关推荐

Search with filters and title

我想搜索custom_post 按标题和ACF字段。所以,我用了WP_Query WordPress函数,但我不能按标题过滤,只能按过滤器过滤。当我提交表单时,我有这样的URL:http://example.com/?s=titre&filter1=condition1&filter2=condition2&filter3=condition3 我的代码:$title = $_GET[\'s\']; $args = array( \'pagenam