Export Posts to a JSON File (WP-CLI)
Adds a "wp export-json" command that writes published posts with their title, slug, dates, content, excerpt, categories, tags, featured image and author to a JSON file, for static sites, apps or archiving.
Opens WPIDE on
Code
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'export-json', function ( $args, $assoc_args ) {
$post_type = sanitize_key( $assoc_args['post_type'] ?? 'post' );
$limit = isset( $assoc_args['limit'] ) ? max( 1, (int) $assoc_args['limit'] ) : -1;
$items = array();
$paged = 1;
do {
$posts = get_posts( array(
'post_type' => $post_type,
'post_status' => 'publish',
'posts_per_page' => -1 === $limit ? 200 : min( 200, $limit ),
'paged' => $paged++,
'no_found_rows' => true,
'orderby' => 'ID',
'order' => 'ASC',
) );
foreach ( $posts as $post ) {
$items[] = array(
'id' => $post->ID,
'title' => get_the_title( $post ),
'slug' => $post->post_name,
'url' => get_permalink( $post ),
'date' => get_post_time( 'c', true, $post ),
'modified' => get_post_modified_time( 'c', true, $post ),
'author' => get_the_author_meta( 'display_name', $post->post_author ),
'excerpt' => wp_strip_all_tags( get_the_excerpt( $post ) ),
'content' => apply_filters( 'the_content', $post->post_content ),
'image' => get_the_post_thumbnail_url( $post, 'full' ) ? get_the_post_thumbnail_url( $post, 'full' ) : null,
'terms' => array(
'categories' => wp_list_pluck( (array) get_the_category( $post->ID ), 'name' ),
'tags' => is_array( get_the_tags( $post->ID ) ) ? wp_list_pluck( get_the_tags( $post->ID ), 'name' ) : array(),
),
);
if ( -1 !== $limit && count( $items ) >= $limit ) {
break 2;
}
}
} while ( count( $posts ) === 200 );
$json = wp_json_encode( $items, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
if ( empty( $assoc_args['file'] ) ) {
WP_CLI::line( $json );
return;
}
if ( false === file_put_contents( $assoc_args['file'], $json ) ) {
WP_CLI::error( 'Could not write the file.' );
}
WP_CLI::success( sprintf( 'Exported %d items to %s.', count( $items ), $assoc_args['file'] ) );
}, array(
'shortdesc' => 'Exports published posts as JSON.',
'synopsis' => array(
array( 'type' => 'assoc', 'name' => 'post_type', 'optional' => true, 'default' => 'post' ),
array( 'type' => 'assoc', 'name' => 'limit', 'optional' => true ),
array( 'type' => 'assoc', 'name' => 'file', 'optional' => true, 'description' => 'Path of the JSON file to write.' ),
),
) );
Notes
Example "wp export-json --post_type=page --file=pages.json"; without --file the JSON is printed.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.