WordPress Restrict Media Library To User Uploads


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







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

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!