Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save musamamasood/e077c47708c0b59350e095183dacdd8c to your computer and use it in GitHub Desktop.
Save musamamasood/e077c47708c0b59350e095183dacdd8c to your computer and use it in GitHub Desktop.
WordPress: Simple, configurable script to export post data to a CSV file
<?php
/**
* Export WordPress post data to CSV
* Based on <http://stackoverflow.com/a/3474698> and <http://ran.ge/2009/10/27/howto-create-stream-csv-php/>
*/
/**
*********************************************************************
* Configuration
*********************************************************************
*/
/**
* Path to WordPress installation root
* Default path './'
*/
// define( 'PATH_TO_WORDPRESS', './' ); # Default WordPress install location
define( 'PATH_TO_WORDPRESS', './wordpress/' ); # Default WordPress sub-directory install location
/**
* Export fields: array of strings representing $post properties to output to CSV.
*/
$export_fields = array(
'post_title',
'post_date'
);
/**
* Export query parameters for WP_Query
* @link http://codex.wordpress.org/Function_Reference/WP_Query WP_Query parameter reference
*/
$export_query = array(
'posts_per_page' => -1,
'post_status' => 'publish',
'post_type' => 'any',
);
/**
*********************************************************************
* Data export
*********************************************************************
*/
// Require WordPress environment
require PATH_TO_WORDPRESS . 'wp-load.php';
// Posts query
$posts = new WP_Query( $export_query );
$posts = $posts->posts;
// Output file stream
$output_filename = 'export_' . strftime( '%Y-%m-%d' ) . '.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' );
// Output data to file
foreach ( $posts as $post ) {
// Get post permalink
switch ( $post->post_type ) {
case 'revision':
case 'nav_menu_item':
break;
case 'page':
$permalink = get_page_link( $post->ID );
break;
case 'post':
$permalink = get_permalink( $post->ID );
break;
case 'attachment':
$permalink = get_attachment_link( $post->ID );
break;
default:
$permalink = get_post_permalink( $post->ID );
break;
}
// Build export array
$post_export = array( $permalink );
foreach ( $export_fields as $export_field ) {
$post_export[] = $post->$export_field;
}
// Add row to file
fputcsv( $output_handle, $post_export );
}
// Close output file stream
fclose( $output_handle );
// We're done!
exit;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment