Building a Hybrid Astro Blog with Headless WordPress and Git-Backed Markdown

In this article (13)
You do not have to choose between a visual content management system and writing articles directly in Git. An Astro website can publish content from headless WordPress alongside local Markdown files. Both sources can appear in one article index and use the same page layout, while retaining different authoring workflows.
The trade-off is additional integration work. A hybrid architecture is not automatically faster, more reliable, or easier to maintain than a single content source. You must define how content is fetched, how URLs are generated, when the site rebuilds, and what happens if WordPress becomes unavailable.
This tutorial demonstrates a small, static-first implementation using Astro’s content collections and the WordPress REST API. It uses separate article URL namespaces to avoid slug collisions, then merges both sources into one listing. The examples are intended as a starting point for a project, not a drop-in integration for every theme or CMS configuration.
When a hybrid content setup makes sense
Consider two publishing workflows:
| Source | Good fit for | What to watch |
|---|---|---|
| WordPress | Editors who prefer Gutenberg, existing article archives, editorial review and media management | API availability at build time, WordPress updates, block markup, media URLs and rebuild automation |
| Git-backed Markdown | Developer notes, documentation, version-controlled tutorials and pull-request review | Contributors need a Git-based workflow; changes require a build and deployment |
For a small site maintained entirely by one developer, Markdown alone may be simpler. For a marketing team that already uses WordPress, staying entirely on WordPress can also be reasonable. Use both when the different authoring needs justify the extra moving parts.
Architecture: two sources, one published site
WordPress editor ── published REST API posts ──┐
├── Astro build
Markdown files ── Git repository ──────────────┘ │
├── /blog/:slug/ (WordPress)
├── /notes/:id/ (Markdown)
└── /articles/ (combined listing)
│
Static deployment
Astro’s default static output generates HTML during a build. Visitors do not need to call the WordPress API to read these pages. That can reduce runtime dependencies, but the build still depends on WordPress unless you explicitly design a fallback.
Scope: The following example uses published standard WordPress posts, Markdown (
.md) files, static output, and public REST endpoints. Draft previews, custom post types, translated sites, and on-demand rendering require additional work.
1. Define a Markdown content collection
Recent Astro releases use src/content.config.ts to define build-time content collections. The built-in glob() loader reads local Markdown files, and a Zod schema checks their frontmatter.
src/content.config.ts
import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';
const notes = defineCollection({
loader: glob({
base: './src/content/notes',
pattern: '**/*.md',
}),
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
draft: z.boolean().default(false),
}),
});
export const collections = { notes };
src/content/notes/debugging-cls.md
---
title: "Debugging Layout Shift in Product Grids"
description: "How to identify unexpected movement in a product listing."
pubDate: 2026-10-29
draft: false
---
## Identify the shifting elements
Start by identifying which elements actually move during loading.
Astro validates the frontmatter against the collection schema. The collection entry’s id derives from the file path; nested Markdown files can produce nested IDs. Draft filtering is an application decision—adding draft: true does not automatically prevent publication unless your routes exclude those entries.
2. Fetch published WordPress posts, including every page
The WordPress REST API exposes standard public posts through /wp-json/wp/v2/posts. Its collection endpoints are paginated: the default page size is 10, the standard maximum is 100, and the X-WP-TotalPages response header reports the total number of pages.
Configure the endpoint in your Astro environment:
.env
WP_POSTS_ENDPOINT=https://cms.example.com/wp-json/wp/v2/posts
The URL is an example. Use your actual WordPress origin. Since this fetch runs during the build, a normal server-side environment variable is appropriate; do not put privileged API credentials into PUBLIC_ environment variables.
src/lib/wordpress.ts
import { decode } from 'html-entities';
import sanitizeHtml from 'sanitize-html';
export interface WpPost {
id: number;
slug: string;
date_gmt: string;
modified_gmt: string;
link: string;
title: { rendered: string };
excerpt: { rendered: string };
content: { rendered: string };
}
export function plainText(html: string): string {
const withoutTags = sanitizeHtml(html, {
allowedTags: [],
allowedAttributes: {},
});
return decode(withoutTags).replace(/\s+/g, ' ').trim();
}
export async function getWpPosts(): Promise<WpPost[]> {
const endpoint = import.meta.env.WP_POSTS_ENDPOINT;
if (!endpoint) {
throw new Error('WP_POSTS_ENDPOINT is not configured');
}
const posts: WpPost[] = [];
let totalPages = 1;
for (let page = 1; page <= totalPages; page++) {
const url = new URL(endpoint);
url.searchParams.set('status', 'publish');
url.searchParams.set('per_page', '100');
url.searchParams.set('page', String(page));
url.searchParams.set('_fields',
'id,slug,date_gmt,modified_gmt,link,title,excerpt,content');
const response = await fetch(url, {
signal: AbortSignal.timeout(15_000),
});
if (!response.ok) {
throw new Error(`WordPress request failed: ${response.status} (${url})`);
}
if (page === 1) {
totalPages = Number(response.headers.get('X-WP-TotalPages'));
if (!Number.isInteger(totalPages) || totalPages < 0) {
throw new Error('Invalid WordPress pagination header');
}
}
const result: unknown = await response.json();
if (!Array.isArray(result)) {
throw new Error('Expected an array of WordPress posts');
}
posts.push(...(result as WpPost[]));
}
return posts;
}
Install the two dependencies used above:
npm install html-entities sanitize-html
npm install -D @types/sanitize-html
The _fields parameter reduces unnecessary response fields. The array check is intentionally lightweight; for production, consider validating individual records with Zod or another runtime schema, especially if plugins modify the REST response. A 15-second timeout is a chosen limit, not a benchmark or guarantee. Add bounded retries for transient failures if your deployment requires them.
Important: The public posts endpoint does not provide a private draft-preview workflow. Don’t embed WordPress administrator credentials in client-side JavaScript to work around that restriction.
3. Use one layout for both article sources
A common Astro layout provides shared metadata and page structure. You can build on this with your site’s existing typography and theme styles.
src/layouts/ArticleLayout.astro
---
interface Props {
title: string;
description: string;
}
const { title, description } = Astro.props;
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{title}</title>
<meta name="description" content={description} />
</head>
<body>
<main class="article-container">
<slot />
</main>
</body>
</html>
Sharing a layout does not automatically normalize all content. WordPress emits HTML (often with wp-block-* classes), while Astro renders Markdown through its content pipeline. You still need CSS for each content pattern, and may need special handling for tables, embeds, image captions, and heading IDs.
4. Generate WordPress article routes safely
A static dynamic route uses getStaticPaths() to decide which URLs Astro generates at build time.
src/pages/blog/[slug].astro
---
import sanitizeHtml from 'sanitize-html';
import ArticleLayout from '../../layouts/ArticleLayout.astro';
import { getWpPosts, plainText, type WpPost } from '../../lib/wordpress';
export async function getStaticPaths() {
const posts = await getWpPosts();
return posts.map((post) => ({
params: { slug: post.slug },
props: { post },
}));
}
const { post } = Astro.props as { post: WpPost };
const title = plainText(post.title.rendered);
const description = plainText(post.excerpt.rendered);
const safeHtml = sanitizeHtml(post.content.rendered, {
allowedTags: [
...sanitizeHtml.defaults.allowedTags,
'img', 'figure', 'figcaption', 'picture', 'source',
],
allowedAttributes: {
...sanitizeHtml.defaults.allowedAttributes,
'*': ['class', 'id'],
img: ['src', 'srcset', 'sizes', 'alt', 'width', 'height', 'loading'],
source: ['srcset', 'sizes', 'type', 'media'],
},
});
---
<ArticleLayout title={title} description={description}>
<article class="prose">
<h1>{title}</h1>
<div set:html={safeHtml} />
</article>
</ArticleLayout>
Astro’s set:html deliberately inserts HTML without escaping it. That is why the example uses an HTML sanitizer and an allowlist before rendering remote content. Review that policy for your editorial needs: it excludes some embeds and styling supported by WordPress blocks. Do not simply enable every tag or attribute to make an embed work.
Also verify that internal WordPress links, image URLs, and canonical tags point to the intended public site—not accidentally to the CMS origin. If WordPress is replacing an existing site, establish a permalink/redirect mapping before launch.
5. Generate Markdown article routes
Markdown is rendered through Astro’s content-collection API. Use a rest parameter ([...id]) so nested file IDs can become valid routes.
src/pages/notes/[...id].astro
---
import { getCollection, render } from 'astro:content';
import ArticleLayout from '../../layouts/ArticleLayout.astro';
export async function getStaticPaths() {
const entries = await getCollection('notes', ({ data }) => !data.draft);
return entries.map((entry) => ({
params: { id: entry.id },
props: { entry },
}));
}
const { entry } = Astro.props;
const { Content } = await render(entry);
---
<ArticleLayout
title={entry.data.title}
description={entry.data.description}
>
<article class="prose">
<h1>{entry.data.title}</h1>
<Content />
</article>
</ArticleLayout>
This creates routes such as /notes/debugging-cls/. It does not create routes for entries marked as drafts. If you use nested paths or custom slugs, confirm the generated IDs and URLs in a production build.
6. Merge both sources into a single article index
Two authoring systems can produce one reader-facing article list. Convert both sources into a small, shared view model, then sort by publication time.
src/pages/articles/index.astro
---
import { getCollection } from 'astro:content';
import { getWpPosts, plainText } from '../../lib/wordpress';
const [notes, wpPosts] = await Promise.all([
getCollection('notes', ({ data }) => !data.draft),
getWpPosts(),
]);
const articles = [
...notes.map((entry) => ({
source: 'Markdown',
title: entry.data.title,
description: entry.data.description,
url: `/notes/${entry.id}/`,
date: entry.data.pubDate,
})),
...wpPosts.map((post) => ({
source: 'WordPress',
title: plainText(post.title.rendered),
description: plainText(post.excerpt.rendered),
url: `/blog/${post.slug}/`,
date: new Date(`${post.date_gmt}Z`),
})),
].sort((a, b) => b.date.getTime() - a.date.getTime());
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Articles</title>
</head>
<body>
<main>
<h1>Articles</h1>
<ul>
{articles.map((article) => (
<li>
<a href={article.url}>{article.title}</a>
<p>{article.description}</p>
<small>
{article.source} ·{' '}
<time datetime={article.date.toISOString()}>
{article.date.toLocaleDateString('en-GB')}
</time>
</small>
</li>
))}
</ul>
</main>
</body>
</html>
This creates a unified listing, not a single underlying content database. The two sources still have different formats and APIs. For a more advanced implementation, normalize authors, categories, tags, hero images, reading time, and search-index content as well. Validate dates rather than silently sorting malformed values.
The example uses /blog/ for WordPress posts and /notes/ for Markdown posts. This avoids a collision when both sources contain an article with the same slug. If you need everything under /blog/, design a collision policy explicitly and test it during the build.
7. Trigger a new build when content changes
With static output, publishing in WordPress does not instantly update the Astro site. The new article appears only after the site rebuilds and deploys successfully. The same applies when a post is unpublished or deleted.
A typical deployment workflow is:
- A Markdown change is merged into the deployment branch; the Git integration starts a build.
- A WordPress article is published, updated, unpublished, or deleted; a trusted webhook or automation triggers a build hook.
- The Astro build fetches WordPress content, generates pages and lists, and deploys the resulting static files.
- A monitoring check verifies that the deployment succeeded and the expected public route appears or disappears.
Cloudflare Pages supports Deploy Hooks for builds triggered by events outside Git. Keep the hook URL secret because anyone holding it may be able to trigger builds. Use event filtering/debouncing to avoid launching a new build for every autosave or minor editorial action. Scheduled WordPress posts need particular attention: your system must trigger a rebuild when they become public, not merely when they are originally scheduled.
Static deployment also means changes to WordPress content, site navigation, or media may require build-time updates. Nothing here inherently guarantees deployment in seconds.
8. Decide what to do when the CMS is unavailable
The original promise of a build that never fails is unrealistic. A production build can fail because of API outages, malformed content, invalid Markdown, dependency updates, deployment limits, or an incorrect environment variable.
You have three reasonable policies:
| Policy | Benefit | Risk |
|---|---|---|
| Fail the build (safest default) | Prevents silently publishing incomplete content | New release cannot deploy until the issue is fixed |
| Use a validated, time-limited snapshot | Can deploy during short CMS outages | May publish outdated or removed content |
| Keep the last successful deployment live | Visitors may continue seeing a working site during a failed build | New content remains unavailable; depends on hosting behavior |
A snapshot should not be a casual catch { return [] }. Returning an empty array can cause a successful build to erase all WordPress-generated pages. If you implement snapshots, record when they were generated, enforce a maximum age, validate their schema, and consider whether unpublished or deleted posts must disappear immediately. Verify your hosting provider’s behavior for failed builds rather than assuming previous releases are always preserved.
9. Checklist before production
- Confirm the public WordPress REST endpoint is accessible and returns only intended posts.
- Test a site with more than 100 posts to verify pagination.
- Test rich WordPress blocks, responsive images, embeds, and unsupported HTML.
- Audit public article URLs, canonical tags, internal links, and redirects.
- Prevent draft Markdown from being included in public routes or indexes.
- Verify slug collisions cannot overwrite another article.
- Test WordPress publish, edit, schedule, unpublish, and delete events.
- Test build behavior when WordPress returns an error or times out.
- Keep deployment hook URLs and any private CMS credentials out of the repository and browser bundle.
- Run a production build and inspect the generated pages before publishing.
What this architecture does—and doesn’t—give you
A WordPress-plus-Markdown setup can be useful when editors need a visual CMS and developers want Git-native documentation. Astro can publish both into one static site with consistent templates and navigation.
But the reliability comes from careful engineering—pagination, validation, safe HTML handling, URL planning, deployment triggers, and failure policies—not from combining the tools alone. Start with the simplest architecture that supports your actual editorial workflow, then add caching, snapshots, search, or custom loaders only when the requirements justify them.
Official documentation and further reading
- Astro: Content collections —
glob(), schemas,getCollection(), andrender(). - Astro: Routing —
getStaticPaths()and static dynamic routes. - Astro: Template directives — security implications of
set:html. - WordPress: REST API posts — published post data and endpoint parameters.
- WordPress: Pagination —
per_page,page, andX-WP-TotalPages. - WordPress: Global parameters —
_fieldsand other response controls. - Cloudflare Pages: Deploy Hooks — rebuilding static sites from CMS events.
Implementation note: Code examples assume a recent Astro version with src/content.config.ts and a Node.js build environment supporting AbortSignal.timeout(). Integrations, sanitization rules, CMS permissions, and hosting behavior should be tested against your own project before production deployment.


