Skip to content

Instantly share code, notes, and snippets.

@harry-wood
Created February 24, 2022 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harry-wood/f39bbecc2ad05787c0b6d22fed72fc33 to your computer and use it in GitHub Desktop.
Save harry-wood/f39bbecc2ad05787c0b6d22fed72fc33 to your computer and use it in GitHub Desktop.
wordpress template code for CSV export based on https://www.gloomycorner.com/export-data-to-csv-in-wordpress-with-php/
<?php /*template name: Export*/
if ( !is_user_logged_in() ) {
auth_redirect();
}
$admin_user = current_user_can('manage_options');
if (!$admin_user) die("ACCESS DENIED");
if (isset($_GET['export'])) {
$table_head = array('column1', 'column2', 'column3');
$table_body = array(
array('a', 'b', 'c'),
array('d', 'e', 'f')
);
$csv = implode( $table_head, ',' );
$csv .= "\n";
foreach($table_body as $row) {
$csv .= implode($row, ',' );
$csv .= "\n";
}
$filename = 'table.csv';
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment; filename="' . $filename .'"' );
header( 'Pragma: no-cache' );
header( "Expires: Sat, 26 Jul 1997 05:00:00 GMT" );
echo "xEFxBBxBF"; // UTF-8 BOM
echo $csv;
exit;
}
global $wpdb;
?>
<h1>Export</h1>
<a href="/export?export=table">Export</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment