Export Users to CSV
Adds an "Export CSV" button to the Users screen that downloads users with their name, email, role and registration date.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.