WordPress to Astro: a guide to migrating or going headless

Published: · Lucas Kleipoedszus
WordPress to Astro workflow: inventory, export, redirects and launch, with headless as the second route

This guide covers both routes from WordPress to Astro: the full migration, after which WordPress is switched off, and headless, where WordPress stays as the editor. Which one fits is covered in Astro or Next.js?.

The code samples work with Astro 6 and 7 (tested with 7.4) and Node.js 22. Replace https://old-site.com with your domain.

Step 1: inventory the old site

Before writing code, list everything that has to move:

  1. Every URL. Since version 5.5, WordPress publishes a sitemap at /wp-sitemap.xml. Yoast and Rank Math usually replace it with /sitemap_index.xml. Also export the pages that get clicks from Search Console: those URLs must not get lost.
  2. Content types. Posts, pages, custom post types, categories, tags.
  3. Plugins that do work. For each plugin decide: replace, rebuild or drop. Contact forms, cookie banners, search, comments and redirect plugins are the usual suspects.
  4. Media. Back up the wp-content/uploads folder via SFTP or from a backup.

Route A: full migration

Create the project

pnpm create astro@latest

Export the content

The WordPress REST API returns all published posts without authentication, at most 100 per request. The total number of pages is in the X-WP-TotalPages header. The script below writes each post as a Markdown file with frontmatter and builds a redirect list. It has no dependencies.

// export-wordpress.mjs – run: node export-wordpress.mjs https://old-site.com
import { mkdir, writeFile } from "node:fs/promises";

const site = process.argv[2].replace(/\/$/, "");
const fields = "slug,date,modified,link,title,excerpt,content";
// WordPress returns titles and excerpts as HTML with entities such as – or  
const entities = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", ndash: "–", mdash: "—", hellip: "…", rarr: "→" };
const text = (html) =>
  html
    .replace(/<[^>]+>/g, "")
    .replace(/&(#x[\da-f]+|#\d+|[a-z]+);/gi, (match, code) =>
      code[0] === "#" ? String.fromCodePoint(Number(code.slice(1).replace(/^x/i, "0x"))) : (entities[code] ?? match),
    )
    .trim();

await mkdir("src/content/posts", { recursive: true });
const redirects = {};

for (let page = 1, total = 1; page <= total; page++) {
  const res = await fetch(`${site}/wp-json/wp/v2/posts?per_page=100&page=${page}&_fields=${fields}`);
  if (!res.ok) throw new Error(`WordPress returned ${res.status} on page ${page}`);
  total = Number(res.headers.get("X-WP-TotalPages") ?? 1);

  for (const post of await res.json()) {
    const legacyPath = new URL(post.link).pathname.replace(/\/$/, "");
    const body = post.content.rendered.replaceAll(`${site}/wp-content/uploads/`, "/wp-content/uploads/");
    const frontmatter = {
      title: text(post.title.rendered),
      description: text(post.excerpt.rendered),
      pubDate: post.date,
      updatedDate: post.modified,
      legacyPath,
    };
    const yaml = Object.entries(frontmatter).map(([key, value]) => `${key}: ${JSON.stringify(value)}`);
    await writeFile(`src/content/posts/${post.slug}.md`, `---\n${yaml.join("\n")}\n---\n\n${body}\n`);
    if (legacyPath !== `/blog/${post.slug}`) redirects[legacyPath] = `/blog/${post.slug}`;
  }
}

await writeFile("redirects.json", `${JSON.stringify(redirects, null, 2)}\n`);
console.log(`${Object.keys(redirects).length} redirects written`);

For pages instead of posts, replace /posts with /pages. The body stays HTML, which Markdown passes through. If you want real Markdown, convert it afterwards with a library such as Turndown. Rare named entities are left as they are; use a library such as he if you need all of them. Spot-check the result: page builder shortcodes sometimes end up as plain text.

Images

Copy the backed-up wp-content/uploads folder to public/wp-content/uploads. Because the script only strips the domain from image URLs, every path stays valid. Later you can move key images to src/assets and optimise them with Astro’s <Image /> component.

Collection and page

The posts become a content collection with a validated schema:

// src/content.config.ts
import { defineCollection } from "astro:content";
import { glob } from "astro/loaders";
import { z } from "astro/zod";

const posts = defineCollection({
  loader: glob({ pattern: "**/*.md", base: "./src/content/posts" }),
  schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.coerce.date(),
    updatedDate: z.coerce.date(),
    legacyPath: z.string(),
  }),
});

export const collections = { posts };
---
// src/pages/blog/[slug].astro
import { getCollection, render } from "astro:content";

export async function getStaticPaths() {
  const posts = await getCollection("posts");
  return posts.map((post) => ({ params: { slug: post.id }, props: { post } }));
}

const { post } = Astro.props;
const { Content } = await render(post);
---
<title>{post.data.title}</title>
<meta name="description" content={post.data.description} />
<article>
  <h1>{post.data.title}</h1>
  <Content />
</article>

In a real project, <title> and the meta tags belong in a shared layout.

Redirects

Astro reads redirects from its config:

// astro.config.mjs
import { defineConfig } from "astro/config";
import { readFileSync } from "node:fs";

const redirects = JSON.parse(readFileSync(new URL("./redirects.json", import.meta.url), "utf8"));

export default defineConfig({
  site: "https://old-site.com",
  redirects,
});

Important: without a server adapter, Astro only produces a meta refresh redirect for static sites, with no status code. For real 301 redirects you have two options: an adapter (Node, Vercel, Netlify and others implement the redirects server-side), or copying the list from redirects.json into your web server config. After launch, check a few old URLs with curl -I: the response must be 301 or 308.

What plugins used to do

  • Sitemap: pnpm astro add sitemap generates it at build time; site must be set in the config.
  • SEO metadata: Yoast exposes each post’s title and description in the REST field yoast_head_json. Add it to fields and take title and description from there instead of the excerpt.
  • Forms: your own endpoint (which needs an adapter) or an external form service.
  • Comments: rarely worth the effort. Export old comments as part of the post and switch new ones off.

Route B: headless with WordPress as the editor

WordPress stays where content is written. Astro fetches it through the REST API at build time.

Load content at build time

A loader defined as a function is enough for most sites. It returns an array of entries with a unique id, and Astro fills the collection with them:

// src/content.config.ts
import { defineCollection } from "astro:content";
import { z } from "astro/zod";

const WP = "https://cms.old-site.com/wp-json/wp/v2";

const posts = defineCollection({
  loader: async () => {
    const entries = [];
    for (let page = 1, total = 1; page <= total; page++) {
      const res = await fetch(`${WP}/posts?per_page=100&page=${page}&_fields=slug,title,content,date,modified`);
      if (!res.ok) throw new Error(`WordPress returned ${res.status}`);
      total = Number(res.headers.get("X-WP-TotalPages") ?? 1);
      for (const post of await res.json()) {
        entries.push({
          id: post.slug,
          title: post.title.rendered,
          html: post.content.rendered,
          pubDate: post.date,
          updatedDate: post.modified,
        });
      }
    }
    return entries;
  },
  schema: z.object({
    title: z.string(),
    html: z.string(),
    pubDate: z.coerce.date(),
    updatedDate: z.coerce.date(),
  }),
});

export const collections = { posts };

Because the content is HTML, render it with set:html:

---
// src/pages/blog/[slug].astro
import { getCollection } from "astro:content";

export async function getStaticPaths() {
  const posts = await getCollection("posts");
  return posts.map((post) => ({ params: { slug: post.id }, props: { post } }));
}

const { post } = Astro.props;
---
<article>
  <h1 set:html={post.data.title} />
  <Fragment set:html={post.data.html} />
</article>

set:html outputs the HTML unchecked. That is acceptable as long as only your own team writes in WordPress.

Rebuild on publish

A static site only learns about new posts on the next build. Almost every hosting platform offers a deploy hook: a secret URL that starts a build. A small must-use plugin calls it whenever a post is published, updated or unpublished:

<?php
// wp-content/mu-plugins/astro-rebuild.php
// In wp-config.php: define('ASTRO_DEPLOY_HOOK', 'https://…');
add_action('transition_post_status', function ($new, $old, $post) {
    if ($new !== 'publish' && $old !== 'publish') {
        return;
    }
    wp_remote_post(ASTRO_DEPLOY_HOOK, ['blocking' => false]);
}, 10, 3);

Drafts and revisions do not trigger a build, because neither the old nor the new status is publish.

Lock WordPress down

  • Move WordPress to its own subdomain, for example cms.old-site.com.
  • Set the WordPress frontend to noindex or redirect it to the new site, otherwise every piece of content exists twice.
  • The REST API stays publicly readable. Previewing drafts requires authentication, for example an application password for a dedicated user with read access.
  • If you prefer GraphQL, install the WPGraphQL plugin. The workflow stays the same.

Launch checklist

  1. Every URL from the inventory returns 200 or redirects with 301/308 to the right target.
  2. Titles, descriptions and canonicals match the old site.
  3. The new sitemap is submitted in Search Console.
  4. Forms arrive, including spam protection.
  5. Images load on mobile and none still points to the old domain.
  6. Compare Search Console and analytics weekly against the pre-migration baseline for the first four weeks.

Sources for all code samples: Astro Content Loader API, Astro redirects, WordPress REST API: posts, REST API pagination.