Skip to content

Instantly share code, notes, and snippets.

@matori
Created December 28, 2019 14:09
Show Gist options
  • Save matori/b0744b6c50f4d78420b64fdca653b3bf to your computer and use it in GitHub Desktop.
Save matori/b0744b6c50f4d78420b64fdca653b3bf to your computer and use it in GitHub Desktop.
WordPressのREST APIで引っ張った全postデータをいい感じに加工してファイルとして出力する
const fs = require("fs")
const dayjs = require("dayjs")
const json = require("./wpdata.json")
console.log(`ファイル数:${json.length}`)
json.forEach((post, index) => {
const date = `${post.date}+09:00`
const modified = `${post.modified}+09:00`
const slug = post.slug
const status = post.status
const title = post.title.rendered
const excerpt = post.excerpt.rendered
const content = post.content.rendered
const filename = getFileName(date, title)
const frontmatter = createFrontmatter({ title, excerpt, slug, date, modified, status })
const fileData = frontmatter + "\n\n" + content
fs.writeFile(`./posts/${filename}`, fileData, err => {
if (err) {
console.log("エラーが発生しました。" + err)
throw err
} else {
console.log(`Success file creation [${index + 1}]: ${filename}`)
}
})
})
function getFileName(date, title) {
const prefix = dayjs(date).format("YYYY-MM-DD")
return `${prefix}-${title}.html`.replace(/\//g, "-")
}
function createFrontmatter(originalData) {
const result = ["<!-- @frontmatter"]
const keys = ["title", "excerpt", "slug", "date", "modified", "category", "status"]
const data = keys.map(key => {
if (key === "excerpt") {
const isExcerpt = originalData[key].includes("[&hellip;]")
return `description: "${isExcerpt ? "" : originalData[key]}"`
}
if (key === "category") {
return `category: [""]`
}
if (key === "title" || key === "slug" || key === "status") {
return `${key}: "${originalData[key]}"`
}
return `${key}: ${originalData[key]}`
})
return result.concat(data, ["-->"]).join("\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment