Headless WordPress · Lesson 20 of 22 · 15 min
WordPress posts as a content collection
Write a custom loader so WordPress feeds your existing blog collection, and every blog page keeps working.
You could call fetchAll() on every page that needs posts. But you already have pages that read from the blog collection: the homepage, /blog, and /blog/[id]. If WordPress can fill that collection, none of those pages need to change.
That’s what a loader does. In lesson 11 you used the built-in glob() loader to read Markdown files. Now you’ll write your own that reads WordPress.
1. Write the loader
src/lib/wordpress-loader.ts
import type { Loader } from 'astro/loaders';
import { fetchAll, decodeEntities, stripHtml, type WPItem } from './wordpress';
interface Options {
type?: 'posts' | 'pages';
limit?: number;
}
export function wordpressLoader({ type = 'posts', limit }: Options = {}): Loader {
return {
name: `wordpress-${type}`,
load: async ({ store, parseData, logger, generateDigest }) => {
logger.info(`Fetching ${type} from WordPress`);
const items = await fetchAll(type, limit);
store.clear();
for (const item of items) {
const data = await parseData({ id: item.slug, data: toData(item) });
store.set({
id: item.slug,
data,
rendered: { html: item.content.rendered },
digest: generateDigest(item.modified_gmt),
});
}
logger.info(`Loaded ${items.length} ${type}`);
},
};
}
function toData(item: WPItem) {
const media = item._embedded?.['wp:featuredmedia']?.[0];
const terms = item._embedded?.['wp:term']?.flat() ?? [];
return {
title: decodeEntities(item.title.rendered),
description: stripHtml(item.excerpt?.rendered ?? ''),
pubDate: `${item.date_gmt}Z`,
tags: terms.map((term) => term.name).filter((name) => name !== 'Uncategorized'),
image: media?.source_url ? { src: media.source_url, alt: media.alt_text ?? '' } : undefined,
};
}
How a loader works
A loader is an object with a name and a load() function. Astro calls load() when the dev server starts and on every build. It hands you some tools:
| Tool | What it’s for |
|---|---|
store |
Where entries go. store.set() adds one, store.clear() empties it. |
parseData() |
Checks your data against the collection’s schema, like frontmatter. |
logger |
Prints to the terminal with the loader’s name in front. |
generateDigest() |
Makes a fingerprint so Astro can skip unchanged entries. |
toData() reshapes a WordPress post into the exact fields your schema already expects: title, description, pubDate, tags. That’s why your components keep working.
id: item.slug means the post’s URL is its WordPress slug. /blog/fall-menu still works if the WordPress slug is fall-menu.
rendered: { html } is the trick that keeps render(post) working. When an entry has rendered HTML, render() turns it into a <Content /> component, just like it did for Markdown.
`${item.date_gmt}Z` adds a Z to mark the date as UTC. Without it, the date would be read in your local time zone.
2. Swap the loader
Update the config. The only changes are the import, the loader line, and a new optional image field.
src/content.config.ts
import { defineCollection } from 'astro:content';
import { z } from 'astro/zod';
import { wordpressLoader } from './lib/wordpress-loader';
const blog = defineCollection({
loader: wordpressLoader({ type: 'posts' }),
schema: z.object({
title: z.string(),
description: z.string(),
pubDate: z.coerce.date(),
tags: z.array(z.string()).default([]),
draft: z.boolean().default(false),
image: z.object({ src: z.string(), alt: z.string() }).optional(),
}),
});
export const collections = { blog };
Delete the src/content/blog/ folder. The Markdown posts aren’t used anymore.
3. Restart and check
Restart npm run dev. The terminal shows:
[wordpress-posts] Fetching posts from WordPress
[wordpress-posts] Loaded 3 posts
Open the homepage, /blog, and a post. Everything works, now powered by WordPress. You didn’t touch a single page or component.