Create a free account to get access to additional free training videos. Enjoy this free video from CraftQuest! Create a free account to get access to additional free training videos. Join the Community

Exporting WordPress Blog with WP JSON API

We learn how to get posts content out of WordPress using the WP JSON API and how we can extend the API to get the data we need in the format we need.

The Word­Press JSON API is a pow­er­ful tool for export­ing post con­tent in JSON for­mat, which can be used for migrat­ing data to Craft CMS. Here are the key points to consider:

  1. Lim­i­ta­tions:

    • No built-in pag­i­na­tion support
    • Only out­puts cat­e­go­ry IDs by default, not names
  2. Access­ing the API:

    • Go to your Word­Press site URL + “/wp-json/w­p/v2/­posts”
    • This end­point pro­vides JSON data for all posts
  3. Import­ing to Craft using Feed Me:

    • Cre­ate a new feed in Feed Me
    • Set the feed URL to your Word­Press JSON API endpoint
    • Map Word­Press fields to Craft fields (title, slug, date, con­tent, etc.)
    • Set unique iden­ti­fiers (e.g., title and slug)
  4. Han­dling Categories:

    • By default, the API only pro­vides cat­e­go­ry IDs
    • To get cat­e­go­ry names, you need to extend the API
  5. Extend­ing the Word­Press JSON API:

    • Add this code to your theme’s functions.php file:
      add_action('rest_api_init', function() {  
      register_rest_field('post', 'category_data', array(  
      'get_callback' => function($post_arr) {  
      	$post_obj = get_post($post_arr['id']);  
      	return get_the_category($post_obj->post_category);  
      },  
      'schema' => array(  
      'description' => __( 'Category Data.'),  
      'type' => 'string'  
      ),  
      ));  
      f});
      
    • This adds a category_​data’ field to the API output
  6. Import­ing Categories:

    • Update your Feed Me con­fig­u­ra­tion to use the new category_​data’ field
    • Map the cat­e­go­ry names and set Feed Me to cre­ate cat­e­gories if they don’t exist

Remem­ber, data manip­u­la­tion dur­ing export is often nec­es­sary when migrat­ing between CMSs. It’s best to pre­pare your data before import­ing it into Craft, allow­ing Feed Me to pull in data in the exact for­mat you need.

For more infor­ma­tion on mod­i­fy­ing Word­Press JSON API respons­es, refer to the Word­Press REST API Hand­book (devel​op​er​.word​press​.org/​r​e​s​t​-api/).

Craft Version
Craft 5
Instructor
Ryan Irelan
Level
Intermediate
Date Published
February 27, 2019
Ryan Irelan

I am the creator of CraftQuest, a web developer, and former software team manager. I spend most of my time improving CraftQuest with code and courses. When I'm not in front of the computer, I spend my time with my family, and running on the roads and trails of Austin, TX.