Halloween Sale 15% off Ends in See the plans
PHP

Export Users to CSV

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

Don’t have WPIDE yet? Install it on your site

Code

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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.