Created
April 30, 2015 10:01
-
-
Save mgmilcher/029e9ebe78cc2e6c8efa to your computer and use it in GitHub Desktop.
WP Export Posts as JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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