2

WordPress: Simple, configurable script to export post data to a CSV file

 2 years ago
source link: https://gist.github.com/robinnorth/5466824
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Simple, configurable script to export post data to a CSV file · GitHub
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; ?>


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK