DEV Community

Cover image for Export WordPress Posts to Nuxt
@lukeocodes πŸ•ΉπŸ‘¨β€πŸ’»
@lukeocodes πŸ•ΉπŸ‘¨β€πŸ’»

Posted on • Updated on

Export WordPress Posts to Nuxt

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 $_
Enter fullscreen mode Exit fullscreen mode

Create a blank file to use as a little CLI.

touch index.js
Enter fullscreen mode Exit fullscreen mode

Initiate the NPM project.

# -y to skip the questions
npm init -y
Enter fullscreen mode Exit fullscreen mode

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

npm install wpapi
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)