Skip to content

Instantly share code, notes, and snippets.

@wkw
Created March 23, 2015 22:43
Show Gist options
  • Save wkw/f5fd77564900f2752624 to your computer and use it in GitHub Desktop.
Save wkw/f5fd77564900f2752624 to your computer and use it in GitHub Desktop.
Export selected fields of all WordPress posts as CSV file
<?php
/*
* Stick this in your functions.php, or include it from a separate file,
* edit the post types you want to export,
* then use the URL: http://your-blog.com/?_inventory=1
*
*/
function return_csv_download($array_data, $filename){
header('Content-Type: text/csv'); // you can change this based on the file type
header('Content-Disposition: attachment; filename="' . $filename . '"');
$out = fopen('php://output', 'w');
foreach($array_data as $row){
fputcsv($out, $row);
}
fclose($out);
}
function _emn_inventory_posts($posttypes){
$args = array(
'posts_per_page' => '-1',
'post_status' => 'publish',
'orderby' => 'date',
'post_type' => ''
);
$out = array();
// @TODO - use data structure which combines titles and the functions to generate
// - the data for the column.
$titles = array('Title', 'Date', 'Permalink', 'Post Type', 'Excerpt', 'Post ID');
array_push($out, $titles);
foreach($posttypes as $type) {
$args['post_type'] = $type;
$query = new WP_Query( $args);
if ( $query->have_posts() ):
while ( $query->have_posts() ): $query->the_post();
$row = array(
get_the_title(),
get_the_date( 'M j, Y' ),
get_permalink(),
$type,
get_the_excerpt(),
get_the_ID()
);
array_push($out, $row);
endwhile;
endif;
wp_reset_postdata();
}
return_csv_download($out, "posts.csv");
//print_r( $out );
}
if( isset($_GET['_inventory']) ){
// =============== EDIT THESE =============
$posttypes = array('newsletter', 'press_release', 'comment_letter', 'in_the_news');
//$posttypes = array('newsletter');
_emn_inventory_posts($posttypes);
die();
}
if( isset($_GET['_get_posttypes']) ){
$args = array(
'public' => true,
'_builtin' => false
);
$posttypes = get_post_types($args);
print_r($posttypes);
die();
}
@Archie22is
Copy link

Thank you :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment