Headless WordPress Blog with Next.js: Simplified Setup
Bhargav Dhameliya
Product Manager at Perrian | WordPress Expert , SEO and Growth Hacker
This guide gets you started with a streamlined Headless WordPress blog powered by Next.js. Keep writing amazing content, and Next.js handles the dynamic frontend.
Prerequisites:
Steps (Simplified):
npx create-next-app my-headless-blog
cd my-headless-blog
2. Install Dependencies:
npm install apollo-client graphql
领英推荐
3. Connect to WordPress API:
NEXT_PUBLIC_WORDPRESS_API_URL=YOUR_WORDPRESS_SITE_URL/graphql
4. Fetch and Display Posts:
import React from 'react';
import gql from 'graphql-tag';
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
const GET_POSTS = gql`
query GetPosts {
posts(where: { status: PUBLISHED }) {
edges {
node {
title
content
featuredImage {
sourceUrl
}
}
}
}
}
`;
const wordpressApiUrl = process.env.NEXT_PUBLIC_WORDPRESS_API_URL;
const client = new ApolloClient({
link: new HttpLink({ uri: wordpressApiUrl }),
cache: new InMemoryCache(),
});
const Home = async () => {
const { data } = await client.query({ query: GET_POSTS });
const posts = data.posts.edges.map(({ node }) => node);
return (
<div>
<h1>My Headless WordPress Blog</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</li>
))}
</ul>
</div>
);
};
export default Home;
Remember: This is a streamlined example. You can add further features like:
With this setup, your WordPress content automatically updates your Next.js blog!