How to restrict users to view only their own media library items in wordpress

By default in WP 3.1.1 any user can view and manage any media library item. Even if it was uploaded by other user. In this howto I described the way to avoid this.

I got the idea from Philip Borisov's plugin. It solves the issue howewer leave total amount of items unchanged: All (58) | Images (44) | Unattached (18)

WordPress Media Library WordPress Media Library

To solve this issue I modified a plugin:

<?php
/*
Plugin Name: Manage Your Media Only
Version: 0.2
*/

//Manage Your Media Only
function mymo_parse_query_useronly( $wp_query ) {
    if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false ) {
        if ( !current_user_can( 'level_5' ) ) {
            global $current_user;
            $wp_query->set( 'author', $current_user->id );
        }
    }
}

add_filter('parse_query', 'mymo_parse_query_useronly' );

/*
 * Count only allowed media library items
 * Added by Vladimir Shugaev <vladimir.shugaev@junvo.com>
 */

add_filter('count_attachments','count_own_attachments');
function count_own_attachments( $default, $mime_type ) {
	global $wpdb, $current_user, $pagenow;


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

    if( 'upload.php' != $pagenow )
        return $default;

    if( !current_user_can('delete_pages') ){
        $and = wp_post_mime_type_where( $mime_type );
		$count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' AND post_author= '$current_user->id' $and GROUP BY post_mime_type", ARRAY_A );
	
		$stats = array( );
		foreach( (array) $count as $row ) {
			$stats[$row['post_mime_type']] = $row['num_posts'];
		}
		$stats['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' AND post_author= '$current_user->id' $and");
		$stats['orphans'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent < 1 AND post_author= '$current_user->id' $and");
		return (object)$stats;
	}
    return $default;
}
?>

Save the code above to manage_your_media_only-v0.2.php, zip it, upload as a plugin to WordPress and activate it.

You also must to modify a couple of files:

In /wp-includes/post.php modify function wp_count_attachments:

function wp_count_attachments( $mime_type = '' ) {
	global $wpdb;

	$and = wp_post_mime_type_where( $mime_type );
	$count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );

	$stats = array( );
	foreach( (array) $count as $row ) {
		$stats[$row['post_mime_type']] = $row['num_posts'];
	}
	$stats['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
	$stats['orphans'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent < 1 $and");

	return apply_filters( 'count_attachments', (object) $stats, $mime_type ); 
}

In /wp-admin/includes/class-wp-media-table.php in function get_views replace

$_total_posts = array_sum($_num_posts) - $_num_posts['trash'];
if ( !isset( $total_orphans ) )
	$total_orphans = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' AND post_parent < 1" );

with

$_total_posts = array_sum($_num_posts) - $_num_posts['trash'] - $_num_posts['orphans'];
if ( !isset( $total_orphans ) )
	$total_orphans = $_num_posts['orphans'];

After that you'll have nice media library with right permission.

  1. City Shopping, May 08, 2011 at 06:40 AM #link Reply

    Nice trick to limit users to their own files only, I just wish I don't have to get into the core files.
    I'm currently using Role Scoper plugin, it works perfectly but seems to be overkill for this particular issue.

  2. Richard Perkins, May 27, 2011 at 02:48 AM #link Reply

    This doesn't work in Wordpres 3.1.3. It worked in 3.1.2 but after and upgrade the file class-wp-media-table.php is no longer there and the file class-wp-media-list-table.php does not have any of this code. Can yo update this for the newest wordpress as I loved the fix. I may have to downgrade back to 3.1.2 just to make it work but i really don't want to.

  3. Richard Perkins, May 31, 2011 at 01:21 AM #link Reply

    My bad, it does work with 3.1.3, I was not doing a good search, sorry.

  4. sonic, Aug 01, 2011 at 04:29 AM #link Reply

    Hi,

    Thanks for the code,

    add_filter('parse_query', 'mymo_parse_query_useronly' ) OR add_action('pre_get_posts','users_own_attachments')

    ONLY EFFECT ON UPLOAD.PHP

    but, when I wrote article and use insert image from media library (media-upload.php), it still show images uploaded by other user, how could I fix it ?

    thanks.

    sonic

  5. Stefania, Oct 04, 2011 at 10:42 AM #link Reply

    To resolve the problem with uploading images in new post I just modified the plugin code this way:

    function my_files_only( $wp_query ) {
    if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false ) {
    if ( !current_user_can( 'level_5' ) ) {
    global $current_user;
    $wp_query->set( 'author', $current_user->id );
    }
    } else if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/media-upload.php' ) !== false ) {
    if ( !current_user_can( 'level_5' ) ) {
    global $current_user;
    $wp_query->set( 'author', $current_user->id );
    }
    }


    }


    With me it's working, and when a user try loading media to insert into post, he only can insert its own files. Now, I'm not such a php or wordpress programmer, so please check this solution and say what you think of it!

  6. Kristjan, Oct 17, 2011 at 05:41 AM #link Reply

    This doesn't work for me. I am running latest version of wordpress and I am always getting "Missing argument 2 for count_own_attachments() in /var/ww..", also the cout displayed is still the slightly huge one.

  7. Kristjan, Oct 17, 2011 at 06:05 AM #link Reply

    Fixed it using this:

    function doit($in){
    list($in,$var2)=$in;
    $var2=true;
    return array($in,$var);
    }

    add_filter('myfilter','doit');
    $changed=false;
    list($in,$changed)=apply_filters('myfilter',array(1,$changed));
    echo $in;
    echo $changed;

    But the items cout still doesn't work in the insert image screen...

  8. Chris, Oct 20, 2011 at 01:42 AM #link Reply

    Doesn´t work for me. It still shows all Mediafiles when I want to insert a featured image.
    And I don´t know where to insert the fixes listed in the comments. Could anyone please post the complete plugin code again? Thanks for the help.

  9. Britt, Mar 23, 2012 at 02:09 PM #link Reply

    Using Stefania's code in the post.php file:

    Using WP 3.3.1 are there it works but all the media files are still showing when creating or editing a posting. Also shows the total number of images on the media library end.

    Does anyone else know how to do this for only showing the postings and the total amount of everyone's? The total amount should only reflect their own. The comments too?

    Need a plugin in to conquer all areas where the Authors can view their won media, postings and comments.

  10. Daniel, May 07, 2012 at 05:29 AM #link Reply

    If you edit the core files all changes will be lost on every update. Very stupid solution.

  11. Daniel, May 07, 2012 at 05:32 AM #link Reply

    A proper solution without change/edit core files (which is always a stupid idea).

    function users_my_media_only( $wp_query ) {
    if ( false !== strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) ) {
    $current_user = wp_get_current_user();
    $current_user = $current_user->ID;
    if ( ! current_user_can( 'manage_options' ) ) {
    global $current_user;
    $wp_query->set( 'author', $current_user->id );
    }
    }
    }
    add_filter('parse_query', 'users_my_media_only' );

  12. Stalking the fat booty, Jan 17, 2013 at 02:34 AM #link Reply

    Woah! I'm really digging the template/theme of this site. It's simple, yet effective.
    A lot of times it's very hard to get that "perfect balance" between superb usability and visual appeal. I must say you have done a fantastic job with this. In addition, the blog loads super quick for me on Chrome. Excellent Blog!

  13. Anjelica Sin - Bra Busters, Jan 24, 2013 at 07:02 PM #link Reply

    First off I would like to say awesome blog! I had a quick question that I'd like to ask if you don't
    mind. I was interested to find out how you center yourself and clear
    your head before writing. I have had a tough time clearing my mind
    in getting my ideas out. I truly do enjoy writing however it just seems like the first 10 to 15 minutes tend to be lost just
    trying to figure out how to begin. Any recommendations or tips?
    Cheers!

  14. Alex, Feb 14, 2013 at 08:03 PM #link Reply

    Hey Guys,

    I just found a plugin in the community that does everything discussed here. I've tested using 3.5.1 and it is working well.

    http://wordpress.org/extend/plugins/view-own-posts-media-only/

    The problem I was having was that the Media Manager Popup window in 3.5 still showed all photos. This set's the default to the specific post's media and then hides the selection. Seems like a little bit of a hack, but it does work. Would be nice if there was a filter on that to show all of the users images but I'll take this as a good start.