Preface
Are you intrigued by the idea of a blazing-fast website but hesitant to abandon the familiarity of WordPress? You’re not alone! Headless WordPress, combined with the modern static site generator Astro, offers the best of both worlds. This guide is designed to gently introduce you to the concept, walk you through the setup, and empower you to start building performant websites without losing your WordPress comfort zone.
Let’s dive in and unlock the potential of Headless WordPress with Astro!
What is Headless WordPress?
Traditionally, WordPress tightly couples the content (the body) with the presentation (the head – the theme). Headless WordPress decouples these two. WordPress becomes a content repository, and a separate frontend technology (in our case, Astro) handles the display. Think of it like this: WordPress is the chef preparing the meal, and Astro is the restaurant plating and serving it.
Benefits of Going Headless
- Improved Performance: Astro builds static websites, which are incredibly fast. No more waiting for PHP to process requests!. Read also how to optimize your website for SEO
- Enhanced Security: Since the frontend is static, there’s less attack surface for vulnerabilities. Your WordPress backend is safely tucked away, serving only content.
- Flexibility and Control: Astro gives you complete control over your frontend. You’re not limited by WordPress themes; you can use modern web technologies and design libraries.
- Future-Proofing: Decoupling your content means you can easily switch to other frontend technologies in the future without migrating your entire website.
What is Astro?
Astro is a modern static site generator designed for building content-focused websites. It’s known for its performance, developer-friendly syntax, and component-based architecture. Astro optimizes for speed by shipping zero JavaScript to the browser by default, unless you explicitly tell it to add interactivity.
Key Features of Astro
- Partial Hydration: Astro allows you to ‘hydrate’ only the interactive parts of your website, leaving the rest as static HTML. This significantly reduces JavaScript overhead.
- Component-Based Architecture: Build your website using reusable components, making development more organized and maintainable.
- Built-in SEO Optimizations: Astro includes features like automatic sitemap generation and optimized asset handling to boost your search engine rankings.
- Easy to Learn: Astro’s syntax is intuitive, particularly if you’re already familiar with HTML, CSS, and JavaScript.
Setting Up Headless WordPress with Astro: A Step-by-Step Guide
1. Prepare Your WordPress Site
- Install WordPress: If you don’t already have a WordPress site, set one up on your preferred hosting provider. Many providers like Bluehost, DreamHost and HostGator offer easy WordPress installation.
- Install the WP REST API Plugin: While WordPress comes with a REST API by default, consider using a plugin like the WP REST API (Version 2) to ensure full functionality. It should be already active and enabled in your wordpress installation. But better check again!
// Check if the WP REST API is enabled function is_rest_api_enabled() { $rest_url = get_rest_url(); if (empty($rest_url)) { return false; // REST API URL is empty, likely not enabled } // Try to access the REST API index route $response = wp_remote_get($rest_url); if (is_wp_error($response)) { return false; // Error occurred, likely REST API is not accessible } $response_code = wp_remote_retrieve_response_code($response); if ($response_code >= 200 && $response_code < 300) { return true; // REST API is accessible } return false; // REST API might not be enabled, or there's some other issue
}
// Usage
if (is_rest_api_enabled()) {
echo ‘REST API is enabled.’;
} else {
echo ‘REST API is not enabled.’;
}
Hint: The WordPress REST API allows external applications like our Astro frontend to fetch content from your WordPress database.
2. Set Up Your Astro Project
-
Create a New Astro Project: Open your terminal and run the following command:
“`bash
npm create astro@latest my-headless-site
“`
Replace `my-headless-site` with your desired project name.
-
Choose a Starter Template (Optional): Astro offers starter templates to kickstart your project. You can choose a blank template or one with pre-configured layouts and components. For example:
npm create astro --template
-
Navigate to Your Project Directory:
“`bash
cd my-headless-site
“`
-
Install Dependencies:
“`bash
npm install
“`
3. Fetch Data from WordPress
- Create an API Utility File: Create a file (e.g.,
src/utils/api.js) to handle fetching data from your WordPress REST API.
// src/utils/api.js
const WORDPRESS_URL = 'YOUR_WORDPRESS_URL/wp-json/wp/v2';
export async function getPosts() {
const res = await fetch(`${WORDPRESS_URL}/posts`);
const posts = await res.json();
return posts;
}
export async function getPostBySlug(slug) {
const res = await fetch(`${WORDPRESS_URL}/posts?slug=${slug}`);
const posts = await res.json();
return posts[0]; // Assuming slugs are unique
}
// Add more functions for fetching other content types (pages, categories, etc.)
Replace `YOUR_WORDPRESS_URL` with the actual URL of your WordPress site.
Hint: Adjust the above functions to fetch other content types like pages, categories, or custom post types. The WP REST API is very powerful. You can fetch almost anything and you can find out how to do this here: WordPress REST API Handbook.
4. Display WordPress Content in Astro
-
Create a Page to Display Posts: In your
src/pagesdirectory, create a new file (e.g.,index.astro) to display your WordPress posts.<!-- src/pages/index.astro --> <html lang='en'> <head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>My Headless WordPress Blog</title> </head> <body> <h1>Latest Posts</h1> <ul> {posts.map(post => ( )) </ul> </body> -
Styling with CSS:
To style your index page, start by creating a CSS file in the public directory. For example, create public/style.css.
Add some basic CSS rules to style the list of posts. For example:
body {
font-family: Arial, sans-serif;
margin: 20px;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin-bottom: 10px;
}
a {
text-decoration: none;
color: #007bff;
}
a:hover {
text-decoration: underline;
}
To apply this stylesheet to your component, import it in the component's script section:
```js
import '../public/style.css';
```
Hint: Do not forget to replace `YOUR_WORDPRESS_URL` with the real and valid link, otherwise it will fail.
### 5. Create Dynamic Routes for Posts
To create individual pages for each post, we’ll use Astro’s dynamic route feature.
-
Create
[slug].astroinsrc/pages:<!-- src/pages/[slug].astro --> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>{post.title.rendered}</title> <h1>{post.title.rendered}</h1> {@html post.content.rendered} export async function getStaticPaths() { const posts = await getPosts(); return posts.map(post => ({ params: { slug: post.slug }, props: { post }, })); } const { post } = Astro.props;
Hint: This code fetches all posts from WordPress during the build process and generates a static page for each one, using the post’s slug as the route.
## Where to go from here?
Now you get the basics about how to create a headless wordpress page with astro, so we can go on and you can learn more:
* **Deploy Your Astro Site:** Deploy your Astro site to a hosting provider like Netlify, Vercel, or Cloudflare Pages. These platforms offer excellent support for static site hosting.
* **Explore Astro Integrations:** Astro has integrations for various frameworks and libraries like React, Vue, and Svelte. Experiment with these integrations to add more interactivity to your website. Also: Make sure that your WordPress website is SEO-friendly, use plugins, keywords et cetera. Read more about SEO here: here.
* **Customize Your Design:** Use CSS, Tailwind CSS, or other styling libraries to create a unique and visually appealing design.
* **Implement Advanced Features:** Explore features like user authentication, comments, and search using APIs and third-party services.
Conclusion
Congratulations! You’ve taken your first steps into the world of Headless WordPress with Astro. By decoupling your content from the presentation, you’ve unlocked a world of possibilities for building fast, secure, and flexible websites. Keep experimenting, exploring, and building!
Remember to visit Start Making Websites, your #1 place for learning the necessary skills with ease and finding valuable resources you need to start making websites today !



