Force a CSV download from a WordPress Plugin

How you can go about forcing 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

Web DevProductivity

Keeping on top of website updates

Learn what website updates are, what they entail, why they are important, and how we can help

Freelancing

Getting the most out of your agency

Here are some tips based on years of working with, for, and as an agency on how to get the most out of any work you do.