0

I have a plugin that generates a CSV file with information from the blog. Now I want users to be able to download this file.

For example when they visit http://example.org/download/information.csv, they get the force download.

I found this solution:

add_action('template_redirect','yoursite_template_redirect');
function yoursite_template_redirect() {
  if ($_SERVER['REQUEST_URI']=='/downloads/data.csv') {
    header("Content-type: application/x-msdownload",true,200);
    header("Content-Disposition: attachment; filename=data.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo 'data';
    exit();
  }
}

But that method is based on a function in the functions.php of the template, but how can I force download a file from a plugin perspective?

3
  • If you're just going to exit execution, you can use a much earlier action, like init, and save some processor cycles.
    – Milo
    Commented Aug 12, 2017 at 18:03
  • How do you mean? Where should I use the init? The WP Codex also uses an exit()
    – Max
    Commented Aug 12, 2017 at 18:37
  • Just put init in place of template_redirect. The example in Codex checks a condition that only exists after the main query happens, so the action that check runs on matters. Your test doesn't depend on anything that happens in the WordPress load sequence. In your case if it's true, it'll be true on the very first and the very last action that's triggered, may as well check early rather than after a bunch of pointless code loads and runs.
    – Milo
    Commented Aug 12, 2017 at 19:20

1 Answer 1

0

That function should work equally well if included in a plugin. template_redirect is an action that fires any time WP parses a URL, it's not exclusive to themes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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