Created
December 19, 2017 12:03
-
-
Save tsertkov/1c14f83c39fd79a0cfc097d13cfcf9bc to your computer and use it in GitHub Desktop.
Import wp-json content using Wordpress REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const got = require('got') | |
async function authenticate (endpoint, username, password) { | |
try { | |
const response = await got(endpoint, { | |
json: true, | |
body: { | |
username, | |
password | |
} | |
}) | |
return response.body.token | |
} catch (error) { | |
console.log(error) | |
throw new Error('Unable to login') | |
} | |
} | |
async function createEntity (endpoint, token, entityType, entity) { | |
try { | |
const response = await got(`${endpoint}/${entityType}`, { | |
json: true, | |
headers: { | |
Authorization: `Bearer ${token}` | |
}, | |
body: entity | |
}) | |
return response.body | |
} catch (error) { | |
console.log(error) | |
throw new Error('Unable create entity') | |
} | |
} | |
async function findEntityBySlug (endpoint, token, entityType, slug) { | |
const response = await got(`${endpoint}/${entityType}`, { | |
json: true, | |
query: { | |
slug | |
}, | |
headers: { | |
Authorization: `Bearer ${token}` | |
} | |
}) | |
return response.body[0] | |
} | |
const endpoint = 'http://localhost/my-content-site/wp-json' | |
const jwtAuthEndpoint = `${endpoint}/jwt-auth/v1/token` | |
const wpJsonEndpoint = `${endpoint}/wp/v2` | |
const username = 'admin' | |
const password = '' | |
;(async () => { | |
const jwtToken = await authenticate(jwtAuthEndpoint, username, password) | |
require('./news_article.json').forEach(async article => { | |
const entity = await findEntityBySlug(wpJsonEndpoint, jwtToken, 'news_article', article.slug) | |
if (entity) { | |
console.log(`Skipping '${article.slug}' - already exists '${article.id}' `) | |
return | |
} | |
const articleToCreate = { | |
date: article.date, | |
slug: article.slug, | |
status: article.status, | |
title: article.title.rendered, | |
fields: { | |
slug: article.acf.slug, | |
meta_title: article.acf.meta_title, | |
meta_description: article.acf.meta_description, | |
content: article.acf.content | |
} | |
} | |
console.log(`Creating '${article.slug}'`) | |
const response = await createEntity(wpJsonEndpoint, jwtToken, 'news_article', articleToCreate) | |
console.log(`Got id '${response.id}'`) | |
}) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment