WordPress 只显示自己上传的媒体图片文件

有时候我们开放用户自己发布文章的权限,但是又不想让媒体库里的所有图片/文件让作者及其以下角色权限的用户看到,怎么办呢?要解决这个问题,将下面的代码添加到当前主题的 functions.php 文件中:

 add_action('pre_get_posts','MBT_restrict_media_library');
 function MBT_restrict_media_library( $wp_query_obj ) {
     global $current_user, $pagenow;
     if( !is_a( $current_user, 'WP_User') )
         return;
     if( 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' )
         return;
     if( !current_user_can('manage_media_library') )
         $wp_query_obj->set('author', $current_user->ID );
     return;
 }

模板兔亲测有效!