0

i need my own download button to get a csv of my users, i know lot of plugins did that but i really need to create mine. I found some post there but i really don't know why mine doesn't work

So i created my admin page with a plugin, and a button to get data and create csv and download, but at the moment when i click, i just have the data back formated for csv but nothing to download the csv file, i really don't understand how to finish this, where i'm wrong. Did i'm on the good way ?

sorry for my english i'm french, this is my class :

class CSVExport {

/**
 * Constructor
 */
public function __construct() {

// Add extra menu items for admins
    add_action('admin_menu', array($this, 'admin_menu'));

// Create end-points
    add_filter('query_vars', array($this, 'query_vars'));
    add_action('parse_request', array($this, 'parse_request'));
    add_action( 'admin_post_download_export_csv', array($this,'download_export_csv') );
    add_action( 'admin_post_nopriv_download_export_csv', array($this,'download_export_csv') );
}

/**
 * Add extra menu items for admins
 */
public function admin_menu() {
    add_menu_page('Download Report', 'Download Report', 'manage_options', 'download_report', array($this, 'download_report'));
    //add_submenu_page( array($this, 'download_report'), 'My Custom Submenu Page', 'My Custom Submenu Page', 'manage_options', array($this, 'download_report_csv'));
}

/**
 * Download report
 */
public function download_report() {
    echo '<div class="wrap">';
    echo '<div id="icon-tools" class="icon32"></div>';
    echo '<h2>Download Report</h2>';

    global $plugin_page,$wpdb;
    if ( isset($_POST['download_csv']) && $plugin_page == 'download_report' ) {
        $wpdb->show_errors();

        // Grab any post values you sent with your submit function
        $DownloadReportFrom = $_POST['ReportDateFrom'];
        $DownloadReportTo = $_POST['ReportDateTo'];

        // Build your query
        $MyQuery = $wpdb->get_results($wpdb->prepare('SELECT * FROM wp_users

    Group by ID',$DownloadReportFrom,$DownloadReportTo));


        // Process report request
        if (! $MyQuery) {
            $Error = $wpdb->print_error();
            die("The following error was found: $Error");
        } else {
            // Prepare our csv download

            // Set header row values
            $csv_fields=array();
            $csv_fields[] = 'Field Name 1';
            $csv_fields[] = 'Field Name 2';
            $output_filename = 'MyReport_' . $DownloadReportFrom .'-'. $DownloadReportTo  . '.csv';
            $output_handle = @fopen( 'php://output', 'w' );

            header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
            header( 'Content-Description: File Transfer' );
            header( 'Content-type: text/csv' );
            header( 'Content-Disposition: attachment; filename=' . $output_filename );
            header( 'Expires: 0' );
            header( 'Pragma: public' );

            $first = true;
            // Parse results to csv format
            foreach ($MyQuery as $row) {

                // Add table headers
                if($first){
                    $titles = array();
                    foreach($row as $key=>$val){
                        $titles[] = $key;
                    }
                    fputcsv($output_handle, $titles);
                    $first = false;
                }

                $leadArray = (array) $row; // Cast the Object to an array
                // Add row to file
                fputcsv( $output_handle, $leadArray );
            }

            //echo '<a href="'.$output_handle.'">test</a>';
            // Close output file stream
            fclose( $output_handle );

            die();
        }
    }

    ?>
    <form method="post" id="download_form" action="">
        <input type="submit" name="download_csv" class="button-primary" value="Download the log (.csv)" />
    </form>
<? }

public function download_export_csv() {
    $wpdb->show_errors();

    // Grab any post values you sent with your submit function
    $DownloadReportFrom = $_POST['ReportDateFrom'];
    $DownloadReportTo = $_POST['ReportDateTo'];

    // Build your query
    $MyQuery = $wpdb->get_results($wpdb->prepare('SELECT * FROM wp_users

    Group by ID',$DownloadReportFrom,$DownloadReportTo));


    // Process report request
    if (! $MyQuery) {
        $Error = $wpdb->print_error();
        die("The following error was found: $Error");
    } else {
        // Prepare our csv download

        // Set header row values
        $csv_fields=array();
        $csv_fields[] = 'Field Name 1';
        $csv_fields[] = 'Field Name 2';
        $output_filename = 'MyReport_' . $DownloadReportFrom .'-'. $DownloadReportTo  . '.csv';
        $output_handle = @fopen( 'php://output', 'w' );

        header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
        header( 'Content-Description: File Transfer' );
        header( 'Content-type: text/csv' );
        header( 'Content-Disposition: attachment; filename=' . $output_filename );
        header( 'Expires: 0' );
        header( 'Pragma: public' );

        $first = true;
        // Parse results to csv format
        foreach ($MyQuery as $row) {

            // Add table headers
            if($first){
                $titles = array();
                foreach($row as $key=>$val){
                    $titles[] = $key;
                }
                fputcsv($output_handle, $titles);
                $first = false;
            }

            $leadArray = (array) $row; // Cast the Object to an array
            // Add row to file
            fputcsv( $output_handle, $leadArray );
        }

        //echo '<a href="'.$output_handle.'">test</a>';
        // Close output file stream
        fclose( $output_handle );

        die();
    }
}

}

// Instantiate a singleton of this plugin
$csvExport = new CSVExport();
  • I'm curious, why did you do a raw database query rather than using WP_User_Query or get_users? Also there's no security checks or validation, anybody might be able to upload a CSV and add their own users – Tom J Nowell Dec 16 '16 at 16:12
  • because when i want to rendering the csv with wordpress data, i got an error like logued in user function not exist, because when the csv file is rendering, there is no wordpress file loaded so i got lot or error :( – 1way Dec 16 '16 at 16:38
  • Have you tried asking about that problem? So you're generating the CSV file but it's displaying in the browser rather than downloding as a file? – Tom J Nowell Dec 16 '16 at 18:19
  • i did another thing :/ i diden't get time to do this well.. so i'll try next time i can :/ thank's for help ! – 1way Jan 6 '17 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.