Restricting Users to View Only Their Own Media Library Items

Here’s a handy code snippet which can be useful to restrict the users to view WordPress media library items they have uploaded. As you can see, we are using manage_options capability to filter users and allow administrators to view all media. To Allow editors to view all media replace manage_options with publish_pages capability.

Useful Read: How To Add URL Column To WordPress Media Library?

add_action('pre_get_posts','restrict_media_library_access');
function restrict_media_library_access( $query ) {
	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_options') )
		$query->set('author', $current_user->ID );

	return;
}

 

0 Comments

Leave a Comment.