This is a script that will export all posts from WordPress using the Rest API and import them into Contentful using the Content Management API.
I've used this script for my own personal site and decided to share it and document my process used to develop it so people can learn from it. The basis of the script is intended to be expanded on for your own specifc purpose, but you can use the script as-is by modifying a few things.
Full write-up can be found here: https://ashcroft.dev/blog/script-migrate-wordpress-posts-contentful/
This script will run in the terminal via Node. You need to have npm installed.
-
Clone the repository
git clone git@github.com:jonashcroft/wp-to-contentful.git cd wp-to-contentful -
Install dependencies
npm install
-
Set up configuration
npm run setup
-
Edit your configuration in relation to WP & Contentful
In your Contentful admin panel:
- Go to Settings → API keys
- Create or select a Content Management API key
- Copy the Space ID and Content Management Token``
- Open
config.jsand update with: a. WordPress:
- endpoint - Rest API endpoint of your WP site
- importPostCount - Number of posts to be processed when running your migrat script
b. Contentful:
- AccessToken - Get the API key from your Contentful https://www.contentful.com/developers/docs/concepts/apis/
- spaceId - YOu can get it from your App's URL https://www.contentful.com/help/spaces/find-space-id/
- environment - by default master
- contentType - blogPost is default but it varies in the your target Contentful site https://www.contentful.com/help/content-types/
- contentFormat - richtext is the default
-
Customize field mapping (if needed)
let fieldData = {
id: postData.id,
type: postData.type,
postTitle: postData.title.rendered,
slug: postData.slug,
content: postData.content.rendered,
publishDate: postData.date_gmt + '+00:00',
featuredImage: postData.featured_media,
tags: getPostLabels(postData.tags, 'tags'),
categories: getPostLabels(postData.categories, 'categories'),
contentImages: getPostBodyImages(postData)
}- Run the migration
npm run migrate
- Never commit sensitive credentials to version control
- The
config.jsfile is automatically excluded from git via.gitignore - Your Contentful access tokens provide full access to your space - keep them secure
- Consider using environment variables in production environments
This project uses config.js to store sensitive configuration data. The following files are included:
config.template.js- Template with example values (safe to commit)config.js- Your actual configuration (excluded from git).env.example- Alternative environment variable setup (if you prefer .env files)
IMPORTANT: There is no sandbox or test environment with this script. If you run this script, it will immediately attempt to publish your new posts and assets - I am not responsible for anything that goes wrong.