Skip links

How to restrict own media per wordPress user without plugin?

You see by default image uploaded to WordPress media library are to be seen everyone logged in and has access to media library. But this will be an issue if you have multiple user, authors, vendors which has their own part.

Today I choose to help you solve that issue without installing any plugin.
You’ll need to add the following code to your WordPress functions.php file or a site-specific plugin.
Is better to add this to a child theme so you won lost this code during updates.

NB: If you don’t have the option to edit your theme or plugins, make sure you disable the security plugin if you are using one e’g siteground security.

// Limit media library access
  
add_filter( 'ajax_query_attachments_args', 'wpb_show_current_user_attachments' );
 
function wpb_show_current_user_attachments( $query ) {
    $user_id = get_current_user_id();
    if ( $user_id && !current_user_can('activate_plugins') && !current_user_can('edit_others_posts
') ) {
        $query['author'] = $user_id;
    }
    return $query;
} 

This code uses current_user_can function to check if the user has the capability to activate plugins or edit other user’s posts. If they don’t, then it changes the query used to display media files and limit it to user’s ID.

Or use the following

Leave a comment

Home
Account
Recent projects
Contact us
Select your currency

Unlock Exclusive Tips & Discounts!

Stay ahead of the curve with Linusite's email newsletter!

Subscription Form