🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
CMS & Integrations••By Komal Nakrani

Headless WordPress with Astro: A Practical Setup

Run headless WordPress with Astro: load posts from the WP REST API with a content loader, render content and images, handle drafts, redirects and rebuilds.

#Astro#WordPress#Headless CMS#Content Layer#REST API

Headless WordPress with Astro means editors keep writing in the WordPress admin while Astro builds the public site from WordPress’s REST API. You fetch posts from /wp-json/wp/v2/posts in a content loader, render the HTML WordPress returns, and trigger an Astro rebuild whenever a post is published. Visitors get static pages; WordPress itself can sit behind a login on a separate domain.

This guide covers the full setup for Astro 7: fetching every page of posts, rendering content and featured images, SEO fields, drafts, redirects and keeping the site in sync.

Key Takeaways

  • WordPress ships a REST API by default, so no plugin is required to go headless.
  • Use _embed to get featured images and authors in the same request, and read X-WP-TotalPages to paginate.
  • Load posts with a custom content loader so pages get typed data from getCollection().
  • content.rendered is HTML; render it with set:html and rewrite image URLs if WordPress lives on another domain.
  • Rebuild on publish with a deploy hook, and copy your old permalink structure so no URL breaks.

Why go headless with WordPress and Astro

The usual reason is speed and security on the front end without retraining editors. Astro outputs plain HTML with zero JavaScript by default, so pages load fast and there’s no PHP or database exposed to visitors. WordPress keeps doing what editors already know: the block editor, media library, users and revisions.

The trade-off is that you lose anything that depends on the WordPress theme layer. Plugins that inject front-end markup (sliders, form builders, some SEO output) no longer render, because WordPress isn’t rendering pages anymore. Comments, search and forms have to be rebuilt in Astro or replaced with services. If that list is long, a headless setup may cost more than it saves. The Markdown vs CMS decision guide helps decide whether you need WordPress at all.

Concern Traditional WordPress Headless WordPress with Astro
Who renders pages PHP theme on each request Astro at build time
Front-end plugins Work Mostly don’t apply
Attack surface for visitors PHP, database, plugins Static files
Content updates Instant After a rebuild (or on-demand rendering)
Editor experience Unchanged Unchanged

The WordPress REST API in two minutes

Every WordPress site since 4.7 exposes /wp-json/wp/v2/. The endpoints you need are:

  • /wp-json/wp/v2/posts for posts
  • /wp-json/wp/v2/pages for pages
  • /wp-json/wp/v2/categories and /tags for taxonomies
  • /wp-json/wp/v2/media for attachments

Useful parameters: per_page (maximum 100), page, _embed (includes featured media, author and terms in _embedded) and _fields (limits the response to named fields). The total page count comes back in the X-WP-TotalPages response header.

curl -I "https://cms.example.com/wp-json/wp/v2/posts?per_page=100"

Look for X-WP-Total and X-WP-TotalPages in the headers. If you’d rather query with GraphQL, the WPGraphQL plugin adds a /graphql endpoint, and the loader below works the same way with a POST request instead.

Load WordPress posts with a content loader

A content loader runs during the build, fetches every post once and stores it in Astro’s data store. The content loaders guide explains the API; here is a WordPress version:

// src/loaders/wordpress.ts
import type { Loader } from 'astro/loaders';

export function wordpressLoader(opts: { url: string; type?: 'posts' | 'pages' }): Loader {
  const type = opts.type ?? 'posts';
  return {
    name: `wordpress-${type}`,
    async load({ store, parseData, generateDigest, logger }) {
      store.clear();
      let page = 1;
      let totalPages = 1;

      do {
        const res = await fetch(`${opts.url}/wp-json/wp/v2/${type}?_embed&per_page=100&page=${page}`);
        if (!res.ok) throw new Error(`WordPress returned ${res.status} for ${type} page ${page}`);
        totalPages = Number(res.headers.get('X-WP-TotalPages') ?? 1);

        for (const item of await res.json()) {
          const media = item._embedded?.['wp:featuredmedia']?.[0];
          const data = await parseData({
            id: item.slug,
            data: {
              title: item.title.rendered,
              excerpt: item.excerpt?.rendered ?? '',
              date: item.date,
              modified: item.modified,
              image: media ? { src: media.source_url, alt: media.alt_text ?? '' } : null,
            },
          });
          store.set({
            id: item.slug,
            data,
            rendered: { html: item.content.rendered },
            digest: generateDigest(item.modified),
          });
        }
        page += 1;
      } while (page <= totalPages);

      logger.info(`Loaded ${store.keys().length} WordPress ${type}`);
    },
  };
}

Passing rendered: { html } to store.set() means you can use Astro’s render() and <Content /> component for the body, just like a Markdown entry.

// src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { wordpressLoader } from './loaders/wordpress';

const posts = defineCollection({
  loader: wordpressLoader({ url: import.meta.env.WP_URL }),
  schema: z.object({
    title: z.string(),
    excerpt: z.string(),
    date: z.coerce.date(),
    modified: z.coerce.date(),
    image: z.object({ src: z.string(), alt: z.string() }).nullable(),
  }),
});

export const collections = { posts };

Note that title.rendered can contain HTML entities such as &#8217; for apostrophes. Decode them in the loader (a small entity map or a library like he) before using titles in <title> tags or Open Graph text.

Render posts in Astro

---
// src/pages/blog/[slug].astro
import { getCollection, render } from 'astro:content';
import BaseLayout from '../../layouts/BaseLayout.astro';

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);
---
<BaseLayout title={post.data.title}>
  <article class="prose">
    <h1 set:html={post.data.title} />
    {post.data.image && <img src={post.data.image.src} alt={post.data.image.alt} loading="eager" />}
    <Content />
  </article>
</BaseLayout>

Block editor output includes classes like wp-block-image and has-text-align-center. WordPress’s block styles don’t come along, so add CSS for the blocks your editors actually use. A short stylesheet covering images, galleries, buttons, columns and embeds handles most sites.

Images and media URLs

Content HTML points at https://cms.example.com/wp-content/uploads/.... You have three choices:

  1. Leave it. Images load from the WordPress server. Simple, but that server must stay public and fast.
  2. Put a CDN in front of uploads. Point wp-content/uploads at an image CDN or offload media to object storage with a plugin, and rewrite the domain in the loader.
  3. Process featured images with astro:assets. Allow the domain in image.remotePatterns and render <Image /> for hero images, while leaving inline content images as they are.
// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  site: 'https://www.example.com',
  image: {
    remotePatterns: [{ protocol: 'https', hostname: 'cms.example.com' }],
  },
});

Rewriting internal links matters too. Links inside posts point to the WordPress domain; replace https://cms.example.com/ with your public site URL in the loader so readers stay on the Astro site.

SEO fields, sitemaps and redirects

If you use Yoast SEO, its REST integration adds a yoast_head_json object to each post with the SEO title, description, canonical and Open Graph data. Rank Math has a similar option. Map those fields in the loader and pass them to your SEO component, so editors keep control of titles and descriptions. The Astro SEO checklist shows a head component to feed them into.

Then let Astro own the technical SEO:

  • Generate the sitemap with @astrojs/sitemap, not the WordPress one.
  • Set the WordPress site to “discourage search engines” or block it with auth, so the CMS domain isn’t indexed as a duplicate.
  • Match your old permalink structure. If posts lived at /2024/05/my-post/, either keep that route shape in Astro or add redirects in astro.config.mjs or your host’s redirect file.

Drafts, previews and rebuilds

The public REST API only returns published posts. To preview drafts, create an Application Password for a WordPress user (Users, Profile, Application Passwords), render a preview route on demand, and fetch with status=draft using Basic auth:

// src/pages/preview/[id].astro (frontmatter)
export const prerender = false;
const auth = btoa(`${import.meta.env.WP_USER}:${import.meta.env.WP_APP_PASSWORD}`);
const res = await fetch(`${import.meta.env.WP_URL}/wp-json/wp/v2/posts/${Astro.params.id}?context=edit`, {
  headers: { Authorization: `Basic ${auth}` },
});

Guard that route so the public can’t use it. For publishing, create a deploy hook at your host and call it when a post changes. A tiny must-use plugin hooking transition_post_status can POST to the hook, or use an existing webhook plugin.

<?php
// wp-content/mu-plugins/astro-rebuild.php
add_action('transition_post_status', function ($new, $old, $post) {
    if ($new === 'publish' || $old === 'publish') {
        wp_remote_post(getenv('ASTRO_DEPLOY_HOOK'), ['blocking' => false]);
    }
}, 10, 3);

For very large sites or near-instant updates, render posts on demand with an adapter and cache responses, or use a live collection so content is fetched per request.

Hosting the two halves

WordPress still needs PHP and MySQL, but it no longer needs to handle public traffic, so a small server is usually fine. The Astro site deploys to any static host; see deploying Astro to static hosts. Put WordPress on a subdomain such as cms.example.com and keep the main domain for Astro.

Many headless WordPress projects are blogs or magazines moving to a faster front end. If that’s yours, the Astro blog and editorial themes already include post layouts, archives and author pages you can wire to this loader. Official references: the WordPress REST API handbook and Astro’s content loader reference.

FAQ

Is headless WordPress with Astro faster than regular WordPress?

For visitors, usually yes, because Astro serves prebuilt HTML with no PHP or database query per request and no theme JavaScript unless you add it. The admin is the same speed as before, and builds take longer as the post count grows.

Do I need WPGraphQL to use WordPress with Astro?

No. The built-in REST API is enough for posts, pages, media and taxonomies. WPGraphQL is useful when you want precise fields, custom post types with complex relations, or fewer requests, but it’s an extra plugin to maintain.

Do WordPress plugins work in a headless Astro site?

Back-end plugins (custom fields, SEO fields, editorial workflow) keep working and can expose data through the API. Plugins that output front-end HTML, scripts or forms don’t, because WordPress no longer renders the pages Astro serves.

How do I update the Astro site when a WordPress post is published?

Create a deploy hook at your host and call it from WordPress when a post’s status changes to or from published. A small must-use plugin on transition_post_status or a webhook plugin does this.

Can I migrate from WordPress to Astro without a CMS at all?

Yes. Export posts to Markdown with a converter, put them in a content collection, and drop WordPress. That suits sites where developers do the writing; keep WordPress headless if editors depend on its admin.