Getting content out of WordPress takes minutes; getting it out clean is the real work. A tested pipeline: raw REST export, Gutenberg block parsing, shortcode mapping, frontmatter and MDX validation.

Getting content out of WordPress takes minutes. Getting it out clean, with headings, images, embeds, captions and SEO fields intact and in a form MDX will compile, is where most of a migration’s effort goes.
This guide is a repeatable pipeline to export WordPress to MDX: export raw content, parse Gutenberg blocks, convert shortcodes, write frontmatter, then validate every file before it ships. It is part of our WordPress to Next.js migration guide, and we ran each script below before publishing it.
For most migrations the authenticated REST API is the best balance. With context=edit on an authenticated request, fields such as title, content and excerpt include a raw value as stored in the database alongside the rendered HTML. WordPress has shipped with Application Passwords since version 5.6, so you can create a credential for the export script from a user’s profile screen without installing anything.
Two REST features make the export lighter. The _fields parameter returns only what you ask for, and since WordPress 5.3 it supports nested properties, so you can request content.raw without content.rendered. And collections are paginated: per_page is capped at 100, and the X-WP-Total and X-WP-TotalPages headers tell you how many pages to fetch.
Before exporting, confirm the API can see everything you need. Custom post types and taxonomies must be registered with show_in_rest. Advanced Custom Fields data is hidden by default: field groups are not visible in the REST API until you opt in, one group at a time. If Yoast SEO is active, it appends yoast_head and yoast_head_json to standard REST responses, which gives you each post’s SEO title, description, canonical and robots settings without a second request.
// Run with: WP_USER=admin WP_APP_PASSWORD='xxxx xxxx xxxx' npx tsx scripts/export-raw.ts
// An Administrator's Application Password: users with context=edit needs list_users
import { mkdir, writeFile } from 'node:fs/promises'
const SITE = 'https://www.example.com'
const AUTH =
'Basic ' + Buffer.from(`${process.env.WP_USER}:${process.env.WP_APP_PASSWORD}`).toString('base64')
// Fields per endpoint; dot notation keeps responses small
const ENDPOINTS: Record<string, string> = {
posts:
'id,slug,link,status,date,date_gmt,modified,modified_gmt,author,categories,tags,featured_media,title.raw,content.raw,excerpt.raw,yoast_head_json,acf',
pages: 'id,slug,link,status,parent,date,date_gmt,modified,modified_gmt,title.raw,content.raw,yoast_head_json,acf',
media: 'id,slug,link,post,source_url,alt_text,caption.raw,media_details',
categories: 'id,slug,name,parent,link',
tags: 'id,slug,name,link',
users: 'id,slug,name,link',
}
async function fetchAll(endpoint: string, fields: string): Promise<unknown[]> {
const items: unknown[] = []
let page = 1
let totalPages = 1
do {
// Add &status=publish,draft,private,future to posts/pages if you need unpublished items
const url = `${SITE}/wp-json/wp/v2/${endpoint}?context=edit&per_page=100&page=${page}&_fields=${fields}`
const res = await fetch(url, { headers: { Authorization: AUTH } })
if (!res.ok) throw new Error(`${res.status} ${res.statusText} for ${url}`)
totalPages = Number(res.headers.get('x-wp-totalpages') ?? '1')
items.push(...((await res.json()) as unknown[]))
page += 1
} while (page <= totalPages)
return items
}
async function main() {
await mkdir('export', { recursive: true })
for (const [endpoint, fields] of Object.entries(ENDPOINTS)) {
const items = await fetchAll(endpoint, fields)
await writeFile(`export/${endpoint}.json`, JSON.stringify(items, null, 2))
console.log(`${endpoint}: ${items.length}`)
}
}
main().catch((err) => {
console.error(err)
process.exit(1)
})Use an Administrator’s Application Password. The users endpoint only answers context=edit for accounts that can list users, so an Editor’s credential fails on the last request.
The media export matters twice over: source_url points at each original upload, and the link and post fields let you redirect attachment pages to their parent posts. If a plugin-added field such as yoast_head_json comes back empty in the edit context on your install, run a second pass for that field with context=view.
Block-editor content is HTML with comment delimiters such as <!-- wp:paragraph --> around each block. Do not strip those with regex. WordPress publishes its own parser on npm, @wordpress/block-serialization-default-parser, which converts a post’s HTML into a block-based structure, with each block’s name, attributes, inner blocks and saved HTML. Content outside any delimiter, including whole classic-editor posts, comes back as a block whose name is null, so one code path handles both editors. One catch: classic content is stored without paragraph tags, which WordPress adds at render time, so those blocks go through autop from @wordpress/autop first or their paragraphs merge into one.

The helpers below rebuild each block’s HTML, convert nested blocks the same way as top-level ones (so an embed inside a group still becomes a component), flag unfamiliar blocks, and convert the rest to Markdown with the unified toolchain. remark-mdx makes the output escape { and < so it also compiles as MDX:
import { autop } from '@wordpress/autop'
import { parse } from '@wordpress/block-serialization-default-parser'
import { unified } from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeRemark from 'rehype-remark'
import remarkGfm from 'remark-gfm'
import remarkMdx from 'remark-mdx'
import remarkStringify from 'remark-stringify'
type ParsedBlock = ReturnType<typeof parse>[number]
const toMarkdown = unified()
.use(rehypeParse, { fragment: true })
.use(rehypeRemark)
.use(remarkGfm) // tables, strikethrough
.use(remarkMdx) // escape { and < so the output also compiles as MDX
.use(remarkStringify)
export const unhandledBlocks = new Map<string, number>()
const PASS_THROUGH = new Set([
'core/paragraph', 'core/heading', 'core/list', 'core/list-item', 'core/quote',
'core/table', 'core/image', 'core/code', 'core/preformatted', 'core/separator',
'core/group', 'core/columns', 'core/column', 'core/freeform', 'core/shortcode',
])
// Saved HTML minus the comment delimiters, with nested blocks converted too
function innerHtml(block: ParsedBlock, components: string[]): string {
let child = 0
return block.innerContent
.map((chunk) => (chunk === null ? blockToHtml(block.innerBlocks[child++], components) : chunk))
.join('')
}
function blockToHtml(block: ParsedBlock, components: string[]): string {
const name = block.blockName
// Classic-editor HTML has no <p> tags until WordPress adds them at render time.
// A bare "<" in prose would make autop merge paragraphs, so escape it first.
if (name === null) return autop(innerHtml(block, components).replace(/<(?![a-zA-Z/!?])/g, '<'))
if (PASS_THROUGH.has(name)) return innerHtml(block, components)
if (name === 'core/embed') {
const url = (block.attrs as { url?: string } | null)?.url
if (!url) return ''
components.push(`<Embed url="${url}" />`)
return `<p>MDXCOMPONENT${components.length - 1}END</p>`
}
unhandledBlocks.set(name, (unhandledBlocks.get(name) ?? 0) + 1)
return innerHtml(block, components) // keep the content; review flagged posts by hand
}
export async function contentToMarkdown(raw: string, components: string[]) {
const html = parse(raw).map((block) => blockToHtml(block, components)).join('\n')
const markdown = String(await toMarkdown.process(html))
// Swap placeholders for JSX after Markdown conversion, so the converter can't mangle them
return markdown.replace(/MDXCOMPONENT(\d+)END/g, (_, i) => components[Number(i)])
}Placeholders made only of letters and digits survive Markdown conversion untouched, which is why components go in at the very end. Print unhandledBlocks after a run: it is your to-do list of block types that need their own handler.
Expect trouble with pages built in a visual builder. They are common: the 2025 Web Almanac found around 60% of WordPress sites use a page builder, and their deeply nested, class-heavy markup converts into noisy Markdown at best. Identify those pages during the inventory and rebuild them as components or CMS-driven layouts instead.
Shortcodes survive in raw content as [tag attr="value"] or [tag]…[/tag]. Count them across the export first, decide what each becomes, then transform them before block parsing:
const SHORTCODE = /\[([a-z_][\w-]*)([^\]]*)\](?:([\s\S]*?)\[\/\1\])?/g
const ATTR = /([\w-]+)=["']([^"']*)["']/g
type Result = { html?: string; jsx?: string }
type Handler = (attrs: Record<string, string>, inner?: string) => Result
const HANDLERS: Record<string, Handler> = {
// [caption]<img …/> Caption text[/caption] → plain HTML figure
caption: (_attrs, inner = '') => {
const img = inner.match(/<img[^>]*>/)?.[0] ?? ''
const text = inner.replace(/<a[^>]*>\s*<img[^>]*>\s*<\/a>|<img[^>]*>/, '').trim()
return { html: `<figure>${img}<figcaption>${text}</figcaption></figure>` }
},
gallery: (attrs) => ({
jsx: `<Gallery ids={[${(attrs.ids ?? '').split(',').map(Number).filter(Boolean).join(', ')}]} />`,
}),
embed: (_attrs, inner = '') => ({ jsx: `<Embed url="${inner.trim()}" />` }),
'contact-form-7': () => ({ jsx: '<ContactForm />' }),
}
export const unknownShortcodes = new Map<string, number>()
export function convertShortcodes(raw: string, components: string[]) {
return raw.replace(SHORTCODE, (match, tag: string, rawAttrs: string, inner?: string) => {
const handler = HANDLERS[tag]
if (!handler) {
unknownShortcodes.set(tag, (unknownShortcodes.get(tag) ?? 0) + 1)
return match // left in place and reported
}
const attrs = Object.fromEntries([...rawAttrs.matchAll(ATTR)].map((m) => [m[1], m[2]]))
const result = handler(attrs, inner)
if (result.html) return result.html
components.push(result.jsx ?? '')
return `<p>MDXCOMPONENT${components.length - 1}END</p>`
})
}The regex is a pragmatic heuristic, not a full shortcode parser: it does not handle nested shortcodes of the same tag, which are rare. Its value is the report. unknownShortcodes tells you exactly which plugins’ output you still need to replace.
Frontmatter is where SEO fields and redirect data live once WordPress is gone. The YAML tab is a practical schema; the Node.js tab writes each post with gray-matter, using .mdx only when the post contains components:
---
title: "Original post title"
slug: "post-name"
date: "2024-03-12T09:30:00Z" # date_gmt plus "Z": WordPress omits the offset
updated: "2025-11-02T14:05:00Z" # modified_gmt plus "Z"
excerpt: "One- or two-sentence summary"
seoTitle: "Title from Yoast, without the site-name suffix"
seoDescription: "Meta description from Yoast"
noindex: false
categories: ["news"]
tags: ["nextjs"]
author: "jane"
coverImage: "/wp-content/uploads/2024/03/cover.jpg"
legacyId: 123
legacyUrl: "/2024/03/post-name/"
---import matter from 'gray-matter'
import { writeFile } from 'node:fs/promises'
export async function writePost(dir: string, slug: string, body: string, data: object, hasComponents: boolean) {
const ext = hasComponents ? 'mdx' : 'md'
await writeFile(`${dir}/${slug}.${ext}`, matter.stringify(body, data))
}Map seoTitle, seoDescription and noindex from yoast_head_json or your SEO plugin’s equivalent. Yoast’s title is the full title tag, usually with your separator and site name, so strip that suffix if your Next.js layout applies a title template, or the brand prints twice. Keep legacyId and legacyUrl on every file: they feed the ID and path redirects.
Copy the complete wp-content/uploads directory from the server or a host backup rather than scraping it, which misses files nothing links to. WordPress stores several resized copies of each image with suffixes such as -300x200.jpg; point content at the originals in each media item’s source_url and let next/image generate responsive sizes. Since WordPress 5.3, very large uploads get a -scaled copy and source_url points at that; the true original is in media_details.original_image when present.
Keeping the /wp-content/uploads/ paths on the new site is the simplest way to avoid image redirects: copy the files into public/wp-content/uploads/, or, for a library of several gigabytes that would bloat every deploy, put them in object storage and add a rewrite for that path. While you are there, use alt_text from the export to find images with no alt text and fix them.

MDX is not forgiving Markdown. HTML comments are not supported (use JavaScript comments in braces instead), and an unescaped < or { has to be escaped, because MDX reads them as the start of JSX or an expression. Void tags need closing (<br />, not <br>), and when MDX renders with React an inline style must be an object, not a string. Legacy WordPress HTML breaks each of those somewhere, which is why ordinary posts are safer as .md: plain Markdown is not parsed as JSX.
Run three automated checks on every converted file:
import { glob, readFile } from 'node:fs/promises' // fs glob needs Node 22+
import matter from 'gray-matter'
import { compile } from '@mdx-js/mdx'
import { z } from 'zod'
const Frontmatter = z.object({
title: z.string().min(1),
slug: z.string().min(1),
date: z.coerce.date(),
updated: z.coerce.date().optional(),
seoDescription: z.string().max(170).optional(),
noindex: z.boolean().default(false),
legacyId: z.number().int(),
legacyUrl: z.string().startsWith('/'),
})
// Matches leftover shortcodes with attributes, e.g. [gallery ids="1,2"]
const LEFTOVER_SHORTCODE = /\[[a-z_][\w-]* [\w-]+=["']/
async function main() {
const failures: string[] = []
for await (const file of glob('content/blog/*.{md,mdx}')) {
const { data, content } = matter(await readFile(file, 'utf8'))
const parsed = Frontmatter.safeParse(data)
if (!parsed.success) failures.push(`${file}: frontmatter ${parsed.error.issues[0]?.message}`)
if (file.endsWith('.mdx')) {
try {
await compile(content)
} catch (error) {
failures.push(`${file}: MDX ${(error as Error).message}`)
}
}
if (LEFTOVER_SHORTCODE.test(content)) failures.push(`${file}: leftover shortcode`)
}
console.log(failures.length ? failures.join('\n') : 'All files valid.')
process.exit(failures.length ? 1 : 0)
}
main()Then run a parity check against the original export. For each post, compare word count, heading count, link count and image count between the source HTML and the converted file, and flag anything that drifts by more than a few per cent. Parity failures are how you catch a gallery that silently disappeared or a table that collapsed into a paragraph.
Not sure your content is worth converting as-is? In a free 15-minute audit we look at your site with you on a live screen-share and tell you what we would rebuild, what we would convert, and what we would drop.
Use deterministic tools for the bulk and keep AI for the leftovers: flagged blocks, unknown shortcodes and MDX compile failures. Models are good at proposing a component mapping for an odd plugin’s output, or rewriting a broken HTML fragment as valid JSX. They are also capable of quietly rewording a sentence, so every AI-touched file goes back through the parity check, and gets a human review if it is a high-traffic page.
When we moved ProEd’s blog from WordPress to Sanity we used the same pattern, scripted import first and hand review after, with Portable Text as the target instead of MDX.
Markdown (.md) for most posts, MDX (.mdx) only for posts that need components such as embeds, galleries or forms. Plain Markdown avoids MDX’s stricter parsing rules, and most Next.js content tools load both formats.
Yes. The block parser returns classic-editor content as a block with a null name. Run it through autop to restore its paragraphs, then the same HTML-to-Markdown step converts it. Classic posts are more likely to contain shortcodes and inline styles, so expect more items in the review queue.
The WXR export includes them. You can render them statically from the exported data, move them to a third-party service, or archive them. Decide before launch, because comment anchors such as #comment-123 sometimes appear in backlinks.
Content Collections, Velite or @next/mdx are the common choices. Velite validates content schemas with Zod and generates TypeScript types. Avoid Contentlayer, which is effectively unmaintained.
A useful first step you can take today: count the shortcodes in your WXR export. The number tells you how much of this pipeline you will actually need.
Our web design team builds Next.js sites and moves WordPress content across, converted, validated and checked against the original. Tell us about your site.
Ready when you are