Skip to content

Instantly share code, notes, and snippets.

@mgmilcher
Created April 30, 2015 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgmilcher/029e9ebe78cc2e6c8efa to your computer and use it in GitHub Desktop.
Save mgmilcher/029e9ebe78cc2e6c8efa to your computer and use it in GitHub Desktop.
WP Export Posts as JSON
<?php
include "wp-load.php";
$posts = new WP_Query('post_type=any&posts_per_page=-1&post_status=publish');
$posts = $posts->posts;
/*
global $wpdb;
$posts = $wpdb->get_results("
SELECT ID,post_type,post_title
FROM {$wpdb->posts}
WHERE post_status<>'auto-draft' AND post_type NOT IN ('revision','nav_menu_item')
");
*/
header('Content-type:text/plain');
// header('Content-Type: application/json');
$output = array();
foreach($posts as $post) {
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;
}
// Categories
$categories = wp_get_post_categories($post->ID);
$cats = array();
foreach($categories as $cat) {
$category = get_category( $cat );
$cats[] = array( 'name' => $category->name );
};
// // Tags
// $tags = wp_get_post_tags($post->ID );
// $tagsList = array();
// foreach($tags as $tag) {
// $tagsList[] = array( 'name' => $tag->name );
// };
// Construct Output
array_push($output, array(
'posts' => array(
'id' => $post->ID,
'type' => $post->post_type,
'date' => $post->post_date,
'permalink' => $permalink,
'title' => $post->post_title,
'post_content' => $post->post_content,
'categories' => $cats,
'tags' => $tagsList
)
));
}
array_push($output, array(
'total_posts' => count($posts)
));
echo json_encode($output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment