# Export Users to CSV

> Adds an "Export CSV" button to the Users screen that downloads users with their name, email, role and registration date.

- Type: PHP
- Runs: Admin only
- Category: [Users](https://wpide.com/library/category/users/)
- Tags: users, export, csv
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/export-users-csv/

## Code

```php
add_action( 'manage_users_extra_tablenav', function ( $which ) {
    if ( 'top' !== $which || ! current_user_can( 'list_users' ) ) {
        return;
    }

    $role = isset( $_GET['role'] ) ? sanitize_key( $_GET['role'] ) : '';
    $url  = wp_nonce_url( admin_url( 'admin-post.php?action=wpide_export_users&role=' . $role ), 'wpide_export_users' );

    echo '<div class="alignleft actions"><a class="button" href="' . esc_url( $url ) . '">Export CSV</a></div>';
} );

add_action( 'admin_post_wpide_export_users', function () {
    if ( ! current_user_can( 'list_users' ) ) {
        wp_die( 'You are not allowed to export users.' );
    }

    check_admin_referer( 'wpide_export_users' );

    $role  = isset( $_GET['role'] ) ? sanitize_key( $_GET['role'] ) : '';
    $users = get_users( array( 'role' => $role, 'orderby' => 'registered', 'order' => 'ASC' ) );
    $safe  = function ( $value ) {
        $value = (string) $value;

        return preg_match( '/^[=+\-@\t\r]/', $value ) ? "'" . $value : $value;
    };

    nocache_headers();
    header( 'Content-Type: text/csv; charset=utf-8' );
    header( 'Content-Disposition: attachment; filename=users-' . gmdate( 'Y-m-d' ) . '.csv' );

    $out = fopen( 'php://output', 'w' );
    fputcsv( $out, array( 'ID', 'Username', 'Email', 'Display name', 'First name', 'Last name', 'Roles', 'Registered' ) );

    foreach ( $users as $user ) {
        fputcsv( $out, array_map( $safe, array(
            $user->ID,
            $user->user_login,
            $user->user_email,
            $user->display_name,
            $user->first_name,
            $user->last_name,
            implode( ', ', (array) $user->roles ),
            $user->user_registered,
        ) ) );
    }

    fclose( $out );
    exit;
} );
```

## Notes

When a role filter is active on the Users screen, only that role is exported.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Export Users to CSV" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
