Restricting users to view only media library items they have uploaded?

I want users to be able to upload photos using add_cap('upload_files') but in their profile page, the Media Library shows every image that’s been uploaded. How can I filter that so that they can only view the images they uploaded?

Here’s my solution for the moment… I’m doing a simple WP query, then a loop on the user’s “Profile” page

$querystr = " SELECT wposts.post_date,wposts.post_content,wposts.post_title, guid 
FROM $wpdb->posts wposts
WHERE wposts.post_author = $author 
AND wposts.post_type="attachment" 
ORDER BY wposts.post_date DESC";

$pageposts = $wpdb->get_results($querystr, OBJECT);

9

You could always filter the media list using a pre_get_posts filter that first determines the page, and the capabilities of the user, and sets the author parameter when certain conditions are met..

Example

add_action('pre_get_posts','users_own_attachments');
function users_own_attachments( $wp_query_obj ) {

    global $current_user, $pagenow;

    $is_attachment_request = ($wp_query_obj->get('post_type')=='attachment');

    if( !$is_attachment_request )
        return;

    if( !is_a( $current_user, 'WP_User') )
        return;

    if( !in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' ) ) )
        return;

    if( !current_user_can('delete_pages') )
        $wp_query_obj->set('author', $current_user->ID );

    return;
}

I used the delete pages cap as a condition so Admins and Editors still see the full media listing.

There is one small side effect, which i can’t see any hooks for, and that’s with the attachment counts shown above the media list(which will still show the total count of media items, not that of the given user – i’d consider this a minor issue though).

Thought i’d post it up all the same, might be useful.. 😉

Leave a Comment