JS Array to CSV Download

Recently I was tasked with generating a CSV file using the data from a table. Normally I would do this in php where the actual data was coming from, but I didn’t see the need to go hacking around on the back-end when this could be done in JS after all the data was loaded. The data was loaded via AJAX, so it took a bit to populate.

The table also uses DataTables to make it pretty, sortable, and paged, but since it was paged I couldn’t just grab the data from the <td>’s. So instead I made an array, then pushed the ‘row’ data to it inside the ajax call. Once all the data is in, the download button appears and you get a CSV file.

Note: This is mostly pulled from a gist example, link is commented in the snippet below.

var csv_arr = [];
// add header first before pushing data
csv.push(["Bruh", "Data", "Date", "Ect"]);

// push some data, I did this inside the ajax call
// mentioned in the copy above
for(var i = 0; i <= somedata.length; i++){
    csv_arr.push(somedata[i]);
}

// found: https://gist.github.com/yangshun/01b81762e8d30f0d7f8f
document.querySelector("#muh_epic_button").addEventListener("click", function (){
    var csvString = csv_arr.join('\r\n'); // Windows newline
    var a = document.createElement('a');
    a.href = 'data:attachment/csv,' + csvString;
    a.target = '_blank';
    a.download = 'data.csv';
    document.body.appendChild(a);
    a.click();
});

GitHub Link

WordPress All Page Listings ShortCode

For when you need a list of all the pages on a WordPress website. Add this to functions.php and use the shortcode [page_listing] to a new Page. This will also create a CSV file in the theme’s directory so you can easily import it into a spreadsheet program like Google Sheets.

<?php 
function page_listing(){
    $pages = get_pages();
    $html = '<ul>';
    $csv_arr = array();
    $csv_arr[] = array("Title", "Permalink", "In Progress", "New/Revised Content Added", "Links Added and Tested", "SEO", "Hero Photo Placed/Cropped Appropriately", "Styling", "Needs Added to Navigation", "Reviewed by NAME (desktop/mobile)", "Reviewed by NAME/NAME", "Assigned to", "Notes", "Page needs to be deleted", "Final Notes Before Launch", "Reviewed by Dev Team");
    foreach($pages as $page){
        $html .= '<li>';
        $html .= $page->post_title .',   <a href="'.get_permalink($page->ID).'">'.get_permalink($page->ID).'</a>';
        $html .= '</li>';
        $csv_arr[] = array($page->post_title, get_permalink($page->ID));
    }
    $html .= '</ul>';
	$fp = fopen(get_template_directory().'/page_listings.csv', 'w');
    foreach($csv_arr as $row){
	    fputcsv($fp, $row);
    }
    fclose($fp);
    return $html;
}
add_shortcode("page_listing", 'page_listing');

GitHub Link