loading...
Cover image for Export WordPress Posts to JAMstack Static Sites

Export WordPress Posts to JAMstack Static Sites

lukeocodes profile image Luke Oliff ・2 min read

If you're reading this, you might have a blog on WordPress right now.

Have you ever had the dream of having your blog on something much faster like a static site generator?

I'm building a Nuxt.js site right now, and I have to import around 800 historical posts going as far back as 2015.

If you've tried to export posts from WordPress, you'll have found there are very little plugins to help you. And, the format of the official export tool seems only designed for importing back into WordPress.

So, I'm building my own little exporter.

What You'll Need

  • A WordPress Blog with WP REST enabled (I don't know how to enable it, it was already enabled! Try it out https://yoursite.com/wp-json) - GET requests are public, no auth required.
  • Some JavaScript/Node Knowledge
  • Node Installed

Creating A Little Exporter

First, a new project directory (and change into it)!

mkdir wp-exporter && cd $_

Create a blank file to use as a little CLI.

touch index.js

Initiate the NPM project.

# -y to skip the questions
npm init -y

Install wpapi the official node SDK for the wp-json API.

npm install wpapi

Now for some coding. Edit index.js and add all of this code.

const WPAPI = require('wpapi')
const fs = require('fs')
const wp = new WPAPI({ endpoint: 'https://yoursite.com/wp-json' })

const wpExportToJson = async () => {
  let page = 1
  let data = {}
  const posts = []

  do {
    try {
      data = await wp.posts().perPage(20).page(page)

      posts.push(...data)
      page++
    } catch (err) {
      console.error(err)
    }
  } while (!!data._paging.links.next)

  fs.writeFile("output.json", JSON.stringify(posts), 'utf8', (err) => {
    if (err) {
      return console.error(err);
    }
    console.log("JSON file has been saved.");
  });
}

wpExportToJson()

By the time you fs.writeFile, the posts variable contains an array of all of your WordPress posts.

If you have a lot of content, this could take a little while to run. The output.json is likely to be big, too. For me, it was over 30MB–and it doesn't even include the images...

From here, you could neatly chop it up into individual JSON files in a Netlify CMS friendly format, or pre-process it before sending it over to a headless CMS like Sanity.io.

Screenshot of WordPress post fetcher CLI

Posted on by:

lukeocodes profile

Luke Oliff

@lukeocodes

60% water. Language champion. JAMStack's biggest fan.

Discussion

markdown guide