Export to CSV from WordPress admin panel

I want to build an admin panel that works like this:

User enters a date range and clicks “Show Report”. The query results are then displayed in the admin panel. User clicks “Export to CSV” and a CSV file is opened showing the same data as the report currently on the screen.

Here’s how it’s currently working:

User enters a date range and clicks “Show Report” and query results are displayed. Date range textboxes are cleared when the report is displayed. User clicks “Export to CSV” and it opens a CSV file with all the headers and formatting in the first 150 lines or so, then the report column titles are shown, and no data (because the date boxes were cleared). In order to get data to pull to the report, the user has to re-enter the date range in the boxes.

The problem is twofold: first, the date boxes are clearing and I want them to retain the value after clicking “Show Report. Second, the output report is showing the html headers and formatting information and I only want it to show the report column titles and data.

I feel like I have all the elements in place, just in the wrong order or something. Any help would be most appreciated!!

Here is the code:

//set admin menu options
add_action(‘admin_menu’, ‘daily_payment_report_menu’);

//add menu page
function daily_payment_report_menu() {
add_menu_page(‘Daily Payment Report’, ‘Daily Payment Report’, ‘manage_options’, ‘daily-payment-report’, ‘pullDailyPaymentReport’);

function pullDailyPaymentReport() {

echo “<h1>Daily Payment Report</h1><br>”;
echo ‘<form action=’ . $_SERVER[‘PHP_SELF’] . ‘?page=daily-payment-report’ . ‘ method=”post”>’;
echo ‘<table>’;
echo ‘<tr><th>Starting Date</th><th>Ending Date</th></tr>’;
echo ‘<tr><td><input type=”text” name=”startdate” placeholder=”MM/DD/YYYY”></td><td><input type=”text” name=”endingdate” placeholder=”MM/DD/YYYY”></td></tr>’;
echo ‘</table>’;
echo ‘<input type=”submit” name=”Display” value=”Show Report” /> <input type=”submit” name=”Export” value=”Export to Excel” />’;
echo ‘</form>’;

global $wpdb;
global $query;
global $startdate;
global $endingdate;

//Set global variables for both operations
if (isset($_POST[‘Display’]) or (isset($_POST[‘Export’]))):

//Store start date and end date from form
$startdate = $_POST[“startdate”];
$endingdate = $_POST[“endingdate”];

$query = “SELECT
DatePaid.meta_value as DatePaid,
Orders.id as OrderNumber,
ItemMeta.meta_value as FileNumber,
Amounts.meta_value as Amount,
CONCAT(GuarFN.meta_value, ‘ ‘, GuarLN.meta_value) as BillingName,
Auth.meta_value as AuthCode
FROM `wpyw_postmeta` Txns
INNER JOIN `wpyw_posts` Orders ON Txns.post_id = Orders.id
INNER JOIN `wpyw_woocommerce_order_items` Items ON Txns.post_id = Items.order_id
INNER JOIN `wpyw_woocommerce_order_itemmeta` ItemMeta ON Items.order_item_id = ItemMeta.order_item_id AND ItemMeta.meta_key = ‘Eagle Recovery File Number’
INNER JOIN `wpyw_postmeta` Amounts ON Txns.post_id = Amounts.post_id AND Amounts.meta_key = ‘_order_total’
INNER JOIN `wpyw_postmeta` DatePaid ON Txns.post_id = DatePaid.post_id AND DatePaid.meta_key = ‘_paid_date’
INNER JOIN `wpyw_postmeta` GuarFN ON Txns.post_id = GuarFN.post_id AND GuarFN.meta_key = ‘_billing_first_name’
INNER JOIN `wpyw_postmeta` GuarLN ON Txns.post_id = GuarLN.post_id AND GuarLN.meta_key = ‘_billing_last_name’
INNER JOIN `wpyw_postmeta` Auth ON Txns.post_id = Auth.post_id AND Auth.meta_key = ‘_wc_usa_epay_credit_card_authorization_code’
WHERE Txns.meta_key = ‘_order_key’ AND STR_TO_DATE(DatePaid.meta_value, ‘%Y-%m-%d’) BETWEEN STR_TO_DATE(‘” . $startdate . “‘, ‘%m/%d/%Y’) AND STR_TO_DATE(‘” . $endingdate . “‘, ‘%m/%d/%Y’);”;//CURDATE() = today


if (isset($_POST[‘Display’])):

$applications = $wpdb->get_results($query);

//Show results table
echo ‘<div>’;
echo “<h1>Daily Payment Report</h1><br>”;
echo $wpdb->num_rows . ” record(s) found”;
echo ‘<table class=”widefat fixed” cellspacing=”0″>’;
echo “<tr><th>Date</th><th>Order Number</th><th>File Number</th><th>Total</th><th>Billing Name</th><th>Auth Code</th></tr>”;

foreach ($applications as $application) {
echo “<tr><td>” . $application->DatePaid . “</td><td>” . $application->OrderNumber . “</td><td>” . $application->FileNumber . “</td><td>” . $application->Amount . “</td><td>” . $application->BillingName . “</td><td>” . $application->AuthCode . “</td></tr>”;

echo “</table>”;
echo “</div>”;

elseif (isset($_POST[‘Export’])):

//Begin attempt at CSV output

//For debugging only:
//echo $query;

$date = date(“Y-m-d”);
$filename = “Web Payment Report”;
$output = fopen(‘php://output’, ‘w’);
$result = $wpdb->get_results($query, ARRAY_A);
fputcsv($output, array(‘DatePaid’, ‘OrderNumber’, ‘FileNumber’, ‘Amount’, ‘BillingName’, ‘AuthCode’));
foreach ($result as $key => $value) {
$modified_values = array(
fputcsv($output, $modified_values);
header(“Pragma: public”);
header(“Expires: 0”);
header(“Cache-Control: must-revalidate, post-check=0, pre-check=0”);
header(“Cache-Control: private”, false);
header(“Content-Type: text/csv; charset=utf-8”);
header(“Content-Disposition: attachment; filename=”” . $date . ” ” . $filename . “.csv”;”);
header(“Content-Transfer-Encoding: binary”);




Read more here:: Export to CSV from WordPress admin panel

Leave a Reply

Your email address will not be published. Required fields are marked *