WordPress Restrict Media Library To User Uploads
WordPress Restrict Media Library To User Uploads
A quick snippet for your Monday morning that I recently used on a site in development. I needed to restrict the media library items to ones specifically uploaded by that user. In order to do so, I utilized the followed placed in the active themes functions.php file:
// restrict media library to users uploads add_filter( 'ajax_query_attachments_args', 'show_current_user_attachments' ); function show_current_user_attachments( $query ) { $user_id = get_current_user_id(); if ( $user_id ) { $query['author'] = $user_id; } return $query; }
Taking this a step further, I also needed to allow subscribers to upload media on the frontend via a post submission form. The following function worked well. I will note that you need to be concerned of security in this situation so necessary steps may need to be taken depending on what kind of application you are building:
add_action('admin_init', 'allow_subscriber_uploads'); function allow_subscriber_uploads() { $subscriber = get_role('subscriber'); $subscriber->add_cap('upload_files'); $subscriber->add_cap('edit_post'); }
Share Your Thoughts