Headless WordPress · Lesson 19 of 22 · 15 min

Connect Astro to WordPress

Store the WordPress address in an environment variable and write a small client that fetches every post.

1. Work on a branch

This module changes where your blog data comes from. Do it on a branch so your Markdown version stays safe:

git checkout -b wordpress

2. Add an environment variable

The WordPress address will be different on your laptop and in production. Keep it out of your code in a .env file at the project root:

.env

WORDPRESS_URL=http://127.0.0.1:9400

And a copy without secrets, so anyone cloning the repo knows what to set:

.env.example

# Your WordPress site's address, with no trailing slash
WORDPRESS_URL=http://127.0.0.1:9400

Check that .gitignore lists .env. The minimal template includes it. Never commit .env.

Astro reads it with import.meta.env.WORDPRESS_URL. Variables without a PUBLIC_ prefix stay on the server and are never sent to the browser.

3. Write the WordPress client

Make a src/lib/ folder for plain TypeScript helpers.

src/lib/wordpress.ts

const WORDPRESS_URL = import.meta.env.WORDPRESS_URL;

export interface WPItem {
  id: number;
  slug: string;
  date_gmt: string;
  modified_gmt: string;
  title: { rendered: string };
  excerpt?: { rendered: string };
  content: { rendered: string };
  _embedded?: {
    'wp:featuredmedia'?: { source_url?: string; alt_text?: string }[];
    'wp:term'?: { name: string; slug: string }[][];
  };
}

/** Fetch every post or page from the WordPress REST API, one page of results at a time. */
export async function fetchAll(type: 'posts' | 'pages', limit?: number): Promise<WPItem[]> {
  if (!WORDPRESS_URL) {
    throw new Error('Missing WORDPRESS_URL. Add it to your .env file.');
  }

  const base = WORDPRESS_URL.replace(/\/$/, '');
  const perPage = Math.min(limit ?? 100, 100);
  const items: WPItem[] = [];
  let page = 1;
  let totalPages = 1;

  do {
    const url = new URL(`${base}/wp-json/wp/v2/${type}`);
    url.searchParams.set('per_page', String(perPage));
    url.searchParams.set('page', String(page));
    url.searchParams.set('_embed', '1');

    const res = await fetch(url);
    if (!res.ok) {
      throw new Error(`WordPress returned ${res.status} for ${url}`);
    }

    items.push(...(await res.json()));
    totalPages = Number(res.headers.get('X-WP-TotalPages') ?? 1);
    page++;
  } while (page <= totalPages && (!limit || items.length < limit));

  return limit ? items.slice(0, limit) : items;
}

/** Turn HTML entities like &#8217; and &amp; back into normal characters. */
export function decodeEntities(text: string): string {
  return text
    .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
    .replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)))
    .replace(/&hellip;/g, '…')
    .replace(/&nbsp;/g, ' ')
    .replace(/&quot;/g, '"')
    .replace(/&(apos|#039);/g, "'")
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&amp;/g, '&');
}

/** Remove HTML tags so an excerpt can be used as plain text. */
export function stripHtml(html: string): string {
  return decodeEntities(html.replace(/<[^>]*>/g, ''))
    .replace(/\s+/g, ' ')
    .trim();
}

What each piece does

WPItem describes the fields you use from the API. TypeScript then autocompletes item.title.rendered and warns you about typos.

fetchAll() handles pagination. WordPress returns at most 100 items per request and tells you how many pages exist in the X-WP-TotalPages header. The loop keeps asking until it has them all. _embed adds the featured image and categories so you don’t need extra requests.

limit is optional. Pointing at a big site to test? fetchAll('posts', 12) grabs just 12.

decodeEntities() fixes titles. WordPress turns Don't into Don&#8217;t. Printed with {title}, Astro would show the entity literally. This turns it back into a real apostrophe.

stripHtml() turns the excerpt (which is wrapped in <p> tags) into plain text for your description field.

4. Quick test

Make a throwaway page to check the connection:

src/pages/wp-test.astro

---
import { fetchAll, decodeEntities } from '../lib/wordpress';

const posts = await fetchAll('posts');
---

<h1>{posts.length} posts from WordPress</h1>
<ul>
  {posts.map((post) => <li>{decodeEntities(post.title.rendered)} ({post.slug})</li>)}
</ul>

With WordPress running, visit localhost:4321/wp-test. You should see your three posts. Delete wp-test.astro once it works.