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

Productivity

Adding issues from other organisations into Github Projects

Let's talk about how you can add issues from other organisations into your Github Project

Slack

Integrating RSS feeds to Slack (including YouTube)

How to add an RSS feed to a Slack channel