WordPress – How to make media library only show current users images

WordPress-MediaLibrary1

The following WordPress function will make the media library only show the current users images, with the exception of Administrators, which can see all images.

add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments' );
function show_current_user_attachments( $query ) {
     $user_id = get_current_user_id(); // get current user ID
     if ( $user_id && !current_user_can('manage_options')) {  // if we have a current user ID (they're logged in) and the current user is not an administrator
         $query['author'] = $user_id; // add author filter, ensures only the current users images are displayed
     }
     return $query;
 }