Exporting Reports to CSV with WordPress

For example you want to export a report containing posts under a specific category ‘uncategorized’ while allowing you to filter the desired date range. Here is how we do it:

download-reports

First we need to enqueue the date picker JS file so that we can use it to our form.

1
2
3
4
5
6
add_action( 'init', 'enqueue_jquery_scripts' );
function enqueue_jquery_scripts() {

    wp_enqueue_script('jquery-ui-datepicker');
    wp_enqueue_style('jquery-ui-css', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
}

Then on our custom page we include a custom script to generate the class that we will be using for our date picker input field.

1
2
3
4
5
6
7
<script type="text/javascript">
    jQuery(document).ready(function($) {
        $('.custom_date').datepicker({
        dateFormat : 'yy-mm-dd'
        });
    });
</script>

Create the form:

1
2
3
4
5
6
7
8
<form method = "post">

    <input type="text" class="custom_date" name="date_from" placeholder = "Date From"/>
    <input type="text" class="custom_date" name="date_to" placeholder = "Date To"/>

    <input type="submit" name="btnDownload" id="submit" class="button-primary" value="Download">

</form>

Finally we create the method that will be handling the post submission

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
if ( $_POST['btnDownload'] ) {

    global $wpdb;

    // Grab any post values you sent with your submit function
    $DownloadFrom = $_POST['date_from'];
    $DownloadTo = $_POST['date_to'];

    $sql_where = "";
    if ( $DownloadFrom != "" &amp;&amp; $DownloadTo != "" ) {
        $sql_where = $wpdb->prepare( " AND datetime BETWEEN %s AND %s ", $DownloadFrom, $DownloadTo );

    }

    // Build your query
    $MyQuery = $wpdb->get_results($wpdb->prepare("
    SELECT p.post_title, p.post_content, p.post_date, p.guid
    FROM wp_posts p
    LEFT JOIN wp_term_relationships tr ON tr.object_id = p.id
    WHERE post_status = 'publish'
    AND tr.term_taxonomy_id = 1
    AND p.id != 0"
.$sql_where, array() ) );

    // Process report request
    if ( !$MyQuery || empty($MyQuery) ) {

        die("Invalid parameters!");
        header ("Refresh: 1; url=" . home_url() . "/yourwebsite/yourformpage" );

    } else {
        // Prepare our csv download

        // Set header row values
        $csv_fields=array();
        $csv_fields[] = 'Title';
        $csv_fields[] = 'Description';
        $csv_fields[] = 'Date Posted';
        $csv_fields[] = 'Link';

        $output_filename = 'MyPosts_' . $DownloadFrom .'-'. $DownloadTo  . '.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' );

        // Insert header row
        fputcsv( $output_handle, $csv_fields );

        // Parse results to csv format
        foreach ($MyQuery as $Result) {
            $leadArray = (array) $Result; // Cast the Object to an array
            // Add row to file
            fputcsv( $output_handle, $leadArray );
            }

        // Close output file stream
        fclose( $output_handle );

        die();
    }
}

Checkout my other WordPress Tutorials by following this LINK



Do you need help with a project? or have a new project in mind that you need help with?

Contact Me