Force a CSV download from a WordPress Plugin

If you are writing a WordPress Plugin and want to automatically download a CSV file when a certain page is hit here is roughly how you go about it.

All this code can sit in your main plugin file, or however you like to organise your plugins.



// Standard code to add a menu item in the admin section
function my_menu() {
    add_menu_page('Download CSV', 'Download CSV', 'add_users', 'my_csv_download', 'csv_download');

}

// Important - Note this is not stored in a function, this is just in the main
// file, if we ran it through a function headers would already get set.
if (isset($_GET['page']) && $_GET['page'] === 'my_csv_download') {
    // Just setting some headers for our download
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false);
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"my_csv.csv\";" );
    header("Content-Transfer-Encoding: binary");
    echo csv(); // Your CSV goes here.
    exit;
}

// This action adds our menu to the main menu structure
add_action('admin_menu', 'my_menu');

Recent posts View all

Talk CSS

FrontEnders - Web Performance

Sharing some of my thoughts on a FrontEnders meetup on the topic of Web Performance

Conferences

Tips for how to ask for time off to attend conferences

Asking for time off to attend a conference can be nerve-racking, these tips will get you closer to attending the conferences you're interested in.