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?
init
, and save some processor cycles.init
in place oftemplate_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.