This is how WordPress and CSV files can work together
One of the most common requirements for WordPress websites is the ability to export data to a CSV file. Whether it's product orders, event registrations, or any other type of data, being able to download this information in a spreadsheet-friendly format is crucial for many businesses.
Fortunately, WordPress makes it relatively straightforward to integrate CSV file exports into your website. In this article, we'll walk through a step-by-step process for creating a WordPress form that allows users to download a CSV report of order status data.
Creating the Export Form
The first step is to create a simple form that users can use to trigger the CSV export. This form can be placed anywhere on your WordPress site, such as on a dedicated "Reports" page or in the footer. Here's an example of what the HTML form code might look like:
<form action="<?php echo site_url() ?>">
<input type="hidden" name="csv_export" value="order_status" />
<input type="text" name="code" />
<input type="submit" value="Download Report" name="download_report" />
</form>
In this form, we have a hidden input field that stores the name of the export we want to generate (order_status
). We also have a text input field where the user can enter a code or other parameter to filter the export data.
When the user clicks the "Download Report" button, the form will submit to the site's homepage (the site_url()
function), passing along the csv_export
and code
parameters.
Listening for the Export Request
Next, we need to add some code to our WordPress functions.php file that will listen for the csv_export
parameter and trigger the CSV export process. Here's an example:
function check_for_export() {
if ( isset( $_GET['csv_export'], $_GET['code'] ) && $_GET['csv_export'] == 'order_status' ) {
ob_end_clean();
export_order_status_csv( $_GET['code'] );
exit();
}
}
add_action('init', 'check_for_export');
In this code, we're using the init
action to call the check_for_export()
function on every page load. This function checks if the csv_export
and code
parameters are set in the URL, and if the csv_export
value is 'order_status'
, it calls the export_order_status_csv()
function, passing in the code
value.
The ob_end_clean()
function is used to clear any existing output buffers, ensuring that nothing else is printed to the browser before we generate the CSV file. Finally, we use the exit()
function to stop any further execution of the script, as we don't want anything else to run after the CSV file has been created.
Generating the CSV File
Now we can implement the export_order_status_csv()
function, which will generate the actual CSV file:
function export_order_status_csv( $code ) {
// Make a DateTime object and get a time stamp for the filename
$date = new DateTime();
$ts = $date->format( "Y-m-d-G-i-s" );
// A name with a time stamp, to avoid duplicate filenames
$filename = "order-statuses-export-$ts.csv";
// Set the appropriate headers for the CSV file
header( 'Pragma: public' );
header( 'Expires: 0' );
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( 'Content-Transfer-Encoding: binary' );
// Open the output buffer as a "file"
$fp = fopen( 'php://output', 'w' );
// Fetch the order status data (this needs to be customized from your end)
$results = new WP_Query();
if ( $results->have_posts() ) {
// Add a BOM to fix UTF-8 encoding issues in Excel
fputs( $fp, chr(0xEF) . chr(0xBB) . chr(0xBF) );
// Set the CSV headers
fputcsv( $fp, [
'orderID',
'orderDate',
'orderTotal'
] );
// Add the data rows to the CSV
while ( $results->have_posts() ) {
$results->the_post();
fputcsv(
$fp,
[
get_the_ID(),
get_the_date(),
'your_custom_data'
]
);
}
wp_reset_query();
fclose( $fp );
} else {
fputcsv( $fp, [ 'No Results' ] );
fclose( $fp );
}
}
This function first generates a unique filename for the CSV file, based on the current date and time. It then sets the appropriate headers to inform the browser that it's receiving a CSV file and that it should prompt the user to download it.
Next, the function opens the output buffer as a "file" using fopen('php://output', 'w')
, which allows us to write directly to the browser's output stream.
The actual data for the CSV file is then generated using a WP_Query
to fetch the order status information. We loop through the results, adding each order's ID, date, and total (or any other custom data you need) to the CSV file using the fputcsv()
function.
Finally, we close the output buffer and return the CSV file to the user.
Reading and Manipulating CSV Data
In some cases, you may need to read data from a CSV file and use it to customize your CSV export. Here's an example of how you can do that using the fgetcsv()
function:
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
In this example, we're opening a CSV file called "test.csv" and looping through each row of data, printing out the number of fields in each row and the value of each field.
You can use this technique to read in data from a CSV file, process it, and then use that information to customize the CSV export that you generate in the export_order_status_csv()
function.
Conclusion
By combining WordPress' built-in functionality with some custom PHP code, you can easily create a CSV export process that allows your users to download data from your website. This can be a powerful tool for providing your users with valuable insights and data, all without the need for any additional libraries or plugins.
If you'd like to take your CSV export process even further, consider integrating it with a tool like Flowpoint.ai, which can help you identify technical issues and user behavior insights that are impacting your website's conversion rates, and automatically generate recommendations to fix them.
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.