Do not point the URL to admin.php
, use admin-post.php
instead:
'<a href="' . admin_url( 'admin-post.php?action=print.csv' ) . '">'
In your plugin register a callback for that action:
add_action( 'admin_post_print.csv', 'print_csv' );
function print_csv()
{
if ( ! current_user_can( 'manage_options' ) )
return;
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
// output the CSV data
}
If you want to make the data available for anonymous users (not logged in), then register the callback again with:
add_action( 'admin_post_nopriv_print.csv', 'print_csv' );
… and remove the capability check from the function.