How to load attachment in media library for current user?

If you want to filter the attachments only at the moment they are being loaded via AJAX, for example when you are setting the post featured image, you can make use of:


function filter_get_the_user_attachments( $query ) {

    $current_user = wp_get_current_user();

    if ( !$current_user ) {
        return;
    }

    $current_user_id = $current_user->ID;

    $query['author__in'] = array(
        $current_user_id
    );

    return $query;

};

add_filter( 'ajax_query_attachments_args', 'filter_get_the_user_attachments', 10 );

Similar to the snippet found in the previous answer but faster.

Also, if you need to filter the attachments which are loaded at the upload.php page you can make use of:


function action_get_the_user_attachments( $query ) {

    // If we are not seeing the backend we quit.
    if ( !is_admin() ) {
        return;
    }

    /**
     * If it's not a main query type we quit.
     *
     * @link    https://codex.wordpress.org/Function_Reference/is_main_query
     */
    if ( !$query->is_main_query() ) {
        return;
    }

    $current_screen = get_current_screen();

    $current_screen_id = $current_screen->id;

    // If it's not the upload page we quit.
    if ( $current_screen_id != 'upload' ) {
        return;
    }

    $current_user = wp_get_current_user();

    $current_user_id = $current_user->ID;

    $author__in = array(
        $current_user_id
    );

    $query->set( 'author__in', $author__in );

}

add_action( 'pre_get_posts', 'action_get_the_user_attachments', 10 );

Hope this helps.