Export to CSV Base Code

Authored by

This is useful if you are needing to create an admin exportable CSV file.  Use this as a base for your code to create an administrator only csv generator.

<?php


// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
 exit;
}

add_action('admin_init', 'export_custom_query_to_csv');

function export_custom_query_to_csv() {
    if (!is_admin() || !current_user_can('manage_options')) return;

    if (!isset($_GET['export_custom_csv'], $_GET['_wpnonce'])) return;

    if (!wp_verify_nonce($_GET['_wpnonce'], 'export_custom_csv_action')) {
        wp_die('Security check failed.');
    }

    global $wpdb;

    $results = $wpdb->get_results("
        SELECT * 
        FROM table
        WHERE date >= CURDATE() - INTERVAL 30 DAY
    ", ARRAY_A);

    if (empty($results)) {
        wp_die('No data found to export.');
    }

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=export-' . date('Y-m-d') . '.csv');

    $output = fopen('php://output', 'w');
    fputcsv($output, array_keys($results[0]));
    foreach ($results as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
    exit;
}

add_action('admin_notices', 'show_csv_export_link');
function show_csv_export_link() {
    if (!current_user_can('manage_options')) return;

    $url = add_query_arg([
        'export_custom_csv' => 1,
        '_wpnonce' => wp_create_nonce('export_custom_csv_action'),
    ], admin_url());

    echo '<div class="notice notice-info"><p>';
    echo 'Download CSV: <a href="' . esc_url($url) . '" target="_blank">Click here to export</a>';
    echo '</p></div>';
}

 

Other Code Snippets

Change Permissions or Ownership of Files or Directories Recursively

Code Snippet | Linux

Sometimes when you are moving files from one host to another, you have to change the files owner or permissions so the web server can utilize it properly.

Read More
Find Files by Size

Code Snippet | Linux

Here is a Linux command line that searches for files that are over a certain size so that you can find where you might be able to free up some space. Useful to find error_logs that have run amok.

Read More
Import MySQL from Command Line

Code Snippet | Linux | MySQL

Here is a method to import a SQL file into a database via the Linux command line.

Read More
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram