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
     $location='/wp/csv-output/?year='.$year.'&month='.$month;
 ?>
 <script>
 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 ?>" });
 </script>

And in my CSV page (again, just a fragment):

   ob_end_clean();
   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.