# Migrate from WordPress

> Move a WordPress site to CMS Orbit: how posts, pages, blocks, categories, media and SEO plugins map, reading everything with the WordPress REST API, splitting post HTML into blocks, and importing it with redirects from every old address.

Source: https://docs.bifrostorbit.com/cms/developers/migrate-from-wordpress/

WordPress keeps a post's body as one piece of HTML, with images, embeds and Gutenberg blocks inside it. CMS Orbit keeps text as rich text and everything else as blocks, so the main work is splitting that HTML. This guide reads the site with the WordPress REST API, turns posts into an import file, and imports them with the script from [Import content with the Management API](https://docs.bifrostorbit.com/cms/developers/import-content/). The examples move the Northwilds journal, a WordPress blog at `journal.northwilds.com`, into a CMS Orbit space.

For the project around it, from the content inventory to the weeks after launch, see [Plan a migration to CMS Orbit](https://docs.bifrostorbit.com/cms/developers/plan-a-migration/).

## How WordPress maps to CMS Orbit

| WordPress | CMS Orbit | Notes |
| --- | --- | --- |
| Site | Space | A multisite network becomes one space per site, or one space with a region per site |
| Post | Entry of a content type such as `journalPost` | |
| Page | Entry of the `page` content type, in folders for its parents | |
| Custom post type | Content type | |
| Gutenberg blocks, shortcodes | Rich text, plus blocks for images, galleries, embeds and anything with layout | |
| Featured image | An Asset field, such as `cover` | |
| Media library | Media library | Alt text per language |
| Categories, tags, custom taxonomies | Taxonomies | Editors can extend them |
| Author | Entry of an `author` content type, referenced from posts | WordPress users are not CMS Orbit users |
| Custom fields, ACF | Fields on the content type | |
| Permalinks | Addresses, with redirects from the old ones | |
| Yoast SEO or Rank Math | The entry's SEO title and description | |
| Menus | Menus | Rebuild them in CMS Orbit, or with `POST /navigation` |
| WPML, Polylang | Languages in a region | Each language holds its own copy of the entry, linked as translations |
| Theme | Your website | CMS Orbit is headless: your website draws the pages |
| Comments | Not yet | Keep them in a comments service |

## Before you start

- The site's REST API at `https://<site>/wp-json/wp/v2/`. Published posts and pages need no sign-in. For drafts and private posts, create an **application password** under **Users › Profile** and send it with HTTP Basic authentication, adding `status=any&context=edit` to the request.
- In CMS Orbit: a space with Staging, a region and every language you need, and a management token that may also manage taxonomies. See "Before you start" in [Import content with the Management API](https://docs.bifrostorbit.com/cms/developers/import-content/).
- Node 20 or later.

## 1. Create the content model

Posts become `journalPost` entries, with the excerpt, date, featured image, author and categories in fields and the body as blocks. Create the journal model from [Schema as code](https://docs.bifrostorbit.com/cms/developers/schema-as-code/), which has the `text` and `imageBlock` components the script uses and a `topics` field for categories. Add a field for each custom field or ACF field you keep.

## 2. Read and transform the posts

The script reads every post with `GET /wp-json/wp/v2/posts?per_page=100&_embed=1`, page by page until `X-WP-TotalPages`. `_embed` brings the author, featured image and terms in the same answer. It creates a `topics` taxonomy with a term per category, splits each post's HTML into blocks, rewrites links between posts to their new addresses, and writes `import.json`:

```js
// wordpress.mjs
import { writeFile } from 'node:fs/promises'
import { call } from './orbit.mjs'

const SITE = process.env.WP_SITE ?? 'https://journal.northwilds.com'

async function all(type) {
  const items = []
  for (let page = 1; ; page += 1) {
    const response = await fetch(`${SITE}/wp-json/wp/v2/${type}?per_page=100&page=${page}&_embed=1`)
    if (!response.ok) throw new Error(`WordPress answered ${response.status} for ${type}`)
    items.push(...(await response.json()))
    if (page >= Number(response.headers.get('x-wp-totalpages') ?? 1)) return items
  }
}

const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', hellip: '…' }
const decode = (text) =>
  text
    .replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code)))
    .replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(parseInt(code, 16)))
    .replace(/&([a-z]+);/g, (match, name) => ENTITIES[name] ?? match)
const plain = (html) => decode(html.replace(/<[^>]+>/g, '')).trim()
const attribute = (html, name) => decode(html.match(new RegExp(`${name}="([^"]*)"`))?.[1] ?? '')

const oldPath = (link) => new URL(link).pathname
const newUrl = (post) => `/journal/${post.slug}`

function body(html, urls) {
  const local = html.replace(/href="([^"]+)"/g, (match, href) => {
    const path = href.startsWith(SITE) ? new URL(href).pathname : null
    return path && urls.has(path) ? `href="${urls.get(path)}"` : match
  })
  const blocks = []
  const parts = local.split(/(<figure[^>]*>[\s\S]*?<\/figure>|<p>\s*<img[^>]*>\s*<\/p>)/)
  for (const part of parts) {
    const img = part.match(/<img[^>]*>/)?.[0]
    if (img && /^<(figure|p)/.test(part)) {
      const caption = part.match(/<figcaption[^>]*>([\s\S]*?)<\/figcaption>/)?.[1]
      blocks.push({
        type: 'imageBlock',
        fields: {
          image: { $asset: { url: attribute(img, 'src'), alt: attribute(img, 'alt') } },
          caption: caption ? plain(caption) : null,
        },
      })
    } else if (part.trim()) {
      blocks.push({ type: 'text', fields: { text: part.trim() } })
    }
  }
  return blocks
}

const posts = await all('posts')
const urls = new Map(posts.map((post) => [oldPath(post.link), newUrl(post)]))

const topics = new Map()
for (const post of posts) {
  for (const term of post._embedded?.['wp:term']?.flat() ?? []) {
    if (term.taxonomy === 'category') topics.set(term.slug, term.name)
  }
}
await call('POST', '/taxonomies', { key: 'topics', name: 'Topics' }).catch((error) => {
  if (error.status !== 409) throw error
})
for (const [value, label] of topics) {
  await call('POST', '/taxonomies/topics/terms', { value, label }).catch((error) => {
    if (error.status !== 409) throw error
  })
}

const authors = new Map()
const entries = posts.map((post) => {
  const author = post._embedded?.author?.[0]
  if (author) authors.set(author.id, author)
  const featured = post._embedded?.['wp:featuredmedia']?.[0]
  return {
    key: `post:${post.id}`,
    type: 'journalPost',
    name: plain(post.title.rendered),
    slug: post.slug,
    url: newUrl(post),
    fields: {
      excerpt: plain(post.excerpt.rendered),
      publishedOn: post.date.slice(0, 10),
      author: author ? { $ref: `author:${author.id}` } : null,
      cover: featured ? { $asset: { url: featured.source_url, alt: featured.alt_text ?? '' } } : null,
      topics: (post._embedded?.['wp:term']?.flat() ?? []).filter((term) => term.taxonomy === 'category').map((term) => term.slug),
    },
    components: body(post.content.rendered, urls),
    ...(post.yoast_head_json
      ? { seo: { title: post.yoast_head_json.title ?? null, description: post.yoast_head_json.description ?? null } }
      : {}),
  }
})

await writeFile('import.json', JSON.stringify({
  environment: 'staging',
  region: 'europe',
  locale: 'en-GB',
  entries: [
    ...[...authors.values()].map((author) => ({
      key: `author:${author.id}`,
      type: 'author',
      name: author.name,
      slug: author.slug,
      fields: { bio: author.description ? `<p>${author.description}</p>` : '' },
    })),
    ...entries,
  ],
  redirects: posts.map((post) => ({ from: oldPath(post.link), to: newUrl(post) })),
}, null, 2))
console.log(`Wrote ${entries.length} posts and ${authors.size} authors to import.json`)
```

```bash
export ORBIT_TOKEN=cms_mt_… ORBIT_ORGANISATION=<organisation id> ORBIT_SPACE=<space id>
WP_SITE=https://journal.northwilds.com node wordpress.mjs
```

The script needs the CMS Orbit variables too, because it creates the taxonomy terms straight away.

What it does with the parts that need thought:

- **Images in the body:** each `<figure>` with an image, and each paragraph holding only an image, becomes an `imageBlock` with the image's `alt` and caption. The HTML between them becomes `text` blocks. CMS Orbit removes images from rich text, so without this step they would be lost.
- **Other Gutenberg blocks:** WordPress sends them rendered as HTML. Headings, paragraphs, lists, quotes and tables stay in rich text. Galleries, embeds such as video, buttons and columns lose their layout or are removed, so add a pattern for each one you use, as for `<figure>`, and map it to a component.
- **Classes and comments:** `class` attributes and other markup that rich text does not keep are removed when CMS Orbit saves the text.
- **Titles and excerpts** arrive with HTML entities such as `&#8217;`; the script decodes them into plain text.
- **Links:** links to other posts on the old site become their new addresses. Links elsewhere stay as they are.
- **Authors** become `author` entries, referenced from each post.
- **SEO:** the `yoast_head_json` that Yoast SEO adds to each post gives the SEO title and description. For Rank Math or another plugin, read its fields instead.
- **Redirects:** every post's old permalink, such as `/2026/01/lofoten-in-winter/`, redirects to its new address under `/journal`.

## 3. Pages and other content

- **Pages:** read `/wp-json/wp/v2/pages` the same way. A page's `parent` is another page, so create a folder for each parent with `POST {locale}/folders` and import the child pages into it, or keep each page's address with `url`. See the [Management API](https://docs.bifrostorbit.com/cms/developers/management-api/).
- **Custom post types** are at `/wp-json/wp/v2/<rest base>` when they are registered with `show_in_rest`.
- **Media:** `/wp-json/wp/v2/media` lists every file, with `source_url` and `alt_text`. The script only uploads files that posts use.
- **Multilingual sites:** WPML and Polylang each add their own language information to the REST API. Read the posts of each language and attach each translation to its main post under `translations` in the import file, with its own name, slug, address and blocks.
- **WordPress export file:** **Tools › Export** gives an XML file (WXR) with posts, pages and attachments. It holds the editor's raw content, with block comments and shortcodes, instead of the rendered HTML, so the REST API is usually easier.

## 4. Import

Check the file with a dry run, then run the import, with `cms-orbit` from [Import content with the Management API](https://docs.bifrostorbit.com/cms/developers/import-content/):

```bash
npx cms-orbit import import.json --dry-run
npx cms-orbit import import.json
```

Check the posts in CMS Orbit on Staging. Then run it again with `--publish`, or publish them in CMS Orbit. Promote them to Production with their redirects as described in [Plan a migration](https://docs.bifrostorbit.com/cms/developers/plan-a-migration/).

## 5. Switch the website

1. Build the website's journal pages with your own components, or start from a quickstart. See [Quickstarts](https://docs.bifrostorbit.com/cms/developers/quickstarts/).
2. Rebuild the menus in CMS Orbit's **Menus**.
3. Promote the content to Production.
4. Point the domain at the new website. Every old permalink then redirects through `resolve`, so search engines and bookmarks find the new pages. See [SEO with the SDK](https://docs.bifrostorbit.com/cms/developers/seo-with-the-sdk/).
5. Keep the WordPress site, read-only, until search engines have picked up the redirects.

## What does not come across

- **Comments.** Not yet in CMS Orbit.
- **Themes, plugins and shortcodes that build pages at request time.** Your website draws the pages; rebuild what they did as components.
- **Revisions.** Each entry starts with one draft.
- **Users.** People sign in with Orbit and get roles in CMS Orbit.
