Redirect from within a WordPress admin page

by Thomas Beutel

I was trying to perform a redirect to generate a CSV file from within a WordPress admin page using the wp_redirect( ) function, but the problem was that I would always get the dreaded “Cannot modify header information – headers already sent” message. This is because admin plugins are simply hooks that are performed within the framework of the admin system.

The solution was to use a Javascript redirect. The Javascript attaches an event listener to listen for the “load” event. When the admin page is finished loading, a page containing the CSV data is loaded. That page has a Content-Type of application/csv, so it downloads immediately, leaving the admin page open (at least in Safari 4).

In my WordPress admin panel (this is a fragment of a plugin):
// setup Javascript redirect
function addListener(element, event, listener, bubble) {
if(element.addEventListener) {
if(typeof(bubble) == "undefined") bubble = false;
element.addEventListener(event, listener, bubble);
} else if(this.attachEvent) {
element.attachEvent("on" + event, listener);
addListener(this, "load", function() { window.location="<?php echo $location ?>" });
addListener(document, "load", function() { window.location="<?php echo $location ?>" });

And in my CSV page (again, just a fragment):
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=contact_data_$year_$month.csv");
header("Pragma: no-cache");
header("Expires: 0");

I found the javascript code here.