0

I have created a download link for my plugin using add_submenu_page. When the link is clicked it gathers some files into a zip, then outputs the contents to the browser like so:

header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file);

The issue is that wordpress by default wraps everything in it's admin theme. Is there a flag or something I can set to tell wordpress that for this particular page I don't want it to out the admin interface?

Edit: Here is the code I used to generate the submenu page:

  add_action('admin_menu', array($this, 'add_download_page'));

  function add_download_page() {
    add_submenu_page( 
        'options.php?post_type=spn_newsletter'
      , 'Download Newsletter' 
      , 'Download Newsletter'
      , 'manage_options'
      , 'spn_download'
      , array($this, 'do_download')
    );
  }
  • Show the code you are using to create this submenu page. – brasofilo Jan 17 '13 at 20:09
2

I think you'll have to hook an earlier action and check if your subpage is being loaded, when the function to render the subpage happens it's too late to send headers. Your subpage's rendering function could just be blank because the earlier action would override it. I tried this with a subpage of themes.php and it seemed like it would work:

function wpa82041_do_download(){
    global $pagenow;
    if( 'themes.php' == $pagenow
    && 'spn_download' == $_GET['page'] ){
        // do your download stuff
    }
}

add_action( 'admin_init', 'wpa82041_do_download' );
  • Wow, very clever, that did exactly what I needed. Thanks. – greatwitenorth Jan 17 '13 at 22:23
  • 1
    Great solution. I used this to generate an XLSX file, then send it using PHP's readfile() function. Don't forget to call exit(0) right after. Otherwise wordpress will produce HTML content which gets appended to the download - this results in an unreadable/corrupt file. – jdhildeb Jan 18 '17 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.