Only show media items the user uploaded

In the Media Library, for the Editor user role, how can we show only media items they uploaded.

  • Luís
    • Support

    Hi allanlove ,

    Hope you're doing well today!

    After the live chat, I made a quick research and found this code and based in what I tested in my site, it works:

    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 (current_user_can('editor') ) {
            $query['author'] = $user_id;
        }
        return $query;
    }

    You can use it on your theme functions.php or in a mu-plugin. I sent attached the mu-plugin I used to test this on my site, if you are interested:

    1) Download the .zip file and unzip it;

    2) Using FTP access, upload hide-media.php to wp-content/mu-plugins. If you don't have a "mu-plugins" folder under "wp-content", please create it.

    I hope this information has been helpful. If I can help you in this or other related question, please let me know!
    Cheers, Luís

  • Ash
    • WordPress Hacker

    Hello allanlove

    Please try the following code:

    add_action('pre_get_posts','users_own_attachments');
    function users_own_attachments( $wp_query_obj ) {
    
        global $current_user, $pagenow;
    
        $is_attachment_request = ($wp_query_obj->get('post_type')=='attachment');
    
        if( !$is_attachment_request )
            return;
    
        if( !is_a( $current_user, 'WP_User') )
            return;
    
        if( !in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' ) ) )
            return;
    
        if( ! current_user_can('administrator') )
            $wp_query_obj->set('author', $current_user->ID );
    
        return;
    }

    Let us know if it works :slight_smile: Hope it helps! Please feel free to ask more questions if you have any.

    Have a nice day!

    Cheers,
    Ash

  • allanlove
    • The Incredible Code Injector

    Hello

    Quick question, could this have an impact on an user role: Editor in pages as they can only view them.

    I have commented out the code and then checked this didn't make any impact but i am sure it worked before hand?

    If not that's ok but any help would be appreciated

    Thank you

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.