Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save walihassanjafferi/3266bab8faef70916c0da2c13df688b2 to your computer and use it in GitHub Desktop.
Save walihassanjafferi/3266bab8faef70916c0da2c13df688b2 to your computer and use it in GitHub Desktop.
CSV Export Wordpress Posts Data
<?php
/**
* Export WordPress post data to CSV
* @author Wali Hassan
*/
/**
* Author's Name Article URL Article Word Count Yoast Readability Score Yoast SEO Score Article Category Article Publish Date
* 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' => 'post',
);
/**
*********************************************************************
* Data export
*********************************************************************
*/
// Require WordPress environment
require_once (ABSPATH . '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' );
$post_export=array();
// Output data to file
foreach ( $posts as $post ) {
$permalink = get_permalink( $post->ID );
// Build export array
$author_id = get_post_field ('post_author', $post->ID);
$display_name = get_the_author_meta( 'display_name' , $author_id );
$count = bavotasan_word_count($post);
$content_score = get_post_meta($post->ID, '_yoast_wpseo_content_score', true );
if ( $content_score <= 70 ){
$content_icon = 'Orange';
}else{
$content_icon = 'Green';
}
$keyword_score = get_post_meta($post->ID, '_yoast_wpseo_linkdex', true );
if ( $keyword_score <= 70 ){
$keyword_icon = 'Orange';
}else{
$keyword_icon = 'Green';
}
$category = get_the_category($post->ID);
$firstCategory = $category[0]->cat_name;
$date = get_the_time('Y-m-d', $post->ID);
$post_export = array(
'author' => ucwords($display_name),
'permalink' => $permalink,
'count' => $count,
'readability score' => $content_icon,
'seo score' => $keyword_icon,
'category' => $firstCategory,
'post_date' => $date,
);
// 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