Skip to content

Instantly share code, notes, and snippets.

@boonebgorges
Created May 13, 2014 18:13
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boonebgorges/79b5d0f628a884cb3b3b to your computer and use it in GitHub Desktop.
Save boonebgorges/79b5d0f628a884cb3b3b to your computer and use it in GitHub Desktop.
WordPress script for doing a .csv export of misc data
<?php
function bbg_csv_export() {
if ( ! is_super_admin() ) {
return;
}
if ( ! isset( $_GET['bbg_export'] ) ) {
return;
}
$filename = 'mcnrc-members-' . time() . '.csv';
$header_row = array(
0 => 'Display Name',
1 => 'Email',
2 => 'Institution',
3 => 'Registration Date',
);
$data_rows = array();
global $wpdb, $bp;
$users = $wpdb->get_results( "SELECT ID, user_email, user_registered FROM {$wpdb->users} WHERE user_status = 0" );
foreach ( $users as $u ) {
$row = array();
$row[0] = bp_core_get_user_displayname( $u->ID );
$row[1] = $u->user_email;
$row[2] = xprofile_get_field_data( 2, $u->ID );
$row[3] = $u->user_registered;
$data_rows[] = $row;
}
$fh = @fopen( 'php://output', 'w' );
fprintf( $fh, chr(0xEF) . chr(0xBB) . chr(0xBF) );
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
header( 'Content-Description: File Transfer' );
header( 'Content-type: text/csv' );
header( "Content-Disposition: attachment; filename={$filename}" );
header( 'Expires: 0' );
header( 'Pragma: public' );
fputcsv( $fh, $header_row );
foreach ( $data_rows as $data_row ) {
fputcsv( $fh, $data_row );
}
fclose( $fh );
die();
}
add_action( 'admin_init', 'bbg_csv_export' );
@allampatu
Copy link

how can i call this function inside wp?

@marcinkieruzel
Copy link

Hi, this is a great snippet. I got it working on local server but on production server it gives me Header already send by output started on line 40. Havent you have same problem?

@Pruthvi222
Copy link

This is difficult to maintain. Can you please suggest dynamic way?

@anjanbrk
Copy link

anjanbrk commented Jun 5, 2023

Fatal error: Uncaught TypeError: fputcsv(): Argument #2 ($fields) must be of type array, string given in

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment