« All posts

Migrating WordPress to Sanity + Next.js: A Technical Walkthrough

A four-stage guide to migrating WordPress content into Sanity and Next.js: export, schema mapping, import scripting, and 301 redirects to preserve SEO.

This walkthrough breaks down a WordPress-to-Sanity-plus-Next.js migration into four concrete stages: exporting content via the WP REST API, mapping WordPress's flat post-type model onto Sanity's typed document schemas, writing an idempotent import script with @sanity/client, and wiring up 301 redirects to preserve the old URL structure. For sites beyond a few hundred posts, the author favors paginated REST API calls over the WXR XML export, and flags that plugin-registered custom post types need to be checked separately via the WP namespace listing.

A key schema detail is storing the original WordPress slug in a seo.legacySlug field on every document, which later makes generating a redirect map via GROQ trivial. The import script separates image uploads, HTML-to-Portable-Text conversion, and document creation into distinct steps, favoring a manual htmlparser2-based mapper over newer conversion libraries for predictability. Prefixing document IDs with wp-post- makes re-running the script safe, and the author recommends testing against a staging dataset with manual spot-checks before touching production.

Finally, legacySlug and new slug pairs are pulled from Sanity via GROQ and exported into a JSON redirect map, wired into next.config.ts's static redirects() for smaller sites or middleware-based lookups for larger ones. The practical payoff for engineers is clear: this approach turns SEO preservation and broken-link risk during a CMS migration into a scriptable, auditable process rather than a manual cleanup task.