Loading WordPress posts in Next.js

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
Search for a command to run...

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
Great article. Loved how you used Graphql here.
Hey Chris, awesome article!
I was looking at some of my upcoming projects and turns I'll be needing to do something similar.
Then I had a thought. Say I had an existing WordPress site and wanted to change the frontend to nextjs... Would that be achievable?
Yes would 100% be James. However bear in mind we need to "rethink" some of the work.
For instance plugins are just a no go, but it it's a traditional site 100% doable.
I have a astro and nextjs starter if you like. You can also hit me up for help.
That's great then! Thank you
Yes, of course. It would ideally be taking the content of the existing site and displaying it with Next.
Oh, cool... I will go have a look at that and absolutely ask you when I need help
Most of you know me for my consistency, a golden arrow in my blog series. I've written 1000 articles in 1008 days! Almost an article a day, and my honeymoon was the only holiday I ever took. I'm super proud of this achievement; it has been a fantasti...

It's not the first time I'll be talking about community. I think it's an essential aspect of any successful tool. This shows in my previous explorations of Astro, Medusa, and now Vendure as well. All these products thrive in a super open, welcoming, ...

The cool part about Vendure is how easy it is to set up and how abstract each layer is. Basically, we get the following elements: External database Server Worker Admin UI Frontend While this is amazing, it also brings a bit of complexity when it co...

The previous article looked at customizing Vendure on a data and process level. In this article, we'll look at customizing emails, as they are often a big part of a webshop system. We'll be looking at two different layers of customization for customi...

Even though Vendure is a pretty significant project out of the box, in some cases, we might want to go in and modify some elements to work to our specific use case. In this article, I'll take a high-level look at some elements we can customize within...

We had a look at how we can use WordPress as a headless CMS with GraphQL as our database point.
We'll let's take that and use that knowledge to create a front-end in Next.js.
Our goal for today is to load our WordPress posts in a Next.js front-end by querying the GraphQL endpoint.
Let's start by adding a .env file to our project. This is a file where we can set up variables specific to the platform we are on.
Create this .env file in the root of your project and add the WordPress URL like so:
WP_URL=http://localhost:8000/graphql
Let's also create a folder called lib. It's where we will add our functions and calls.
Inside this lib folder, create a file called api.js. This file will act as the main source of our API communication.
The first thing we need in this file is the WordPress URL we just set.
const API_URL = process.env.WP_URL;
Then we want a generic GraphQL request. Since we can send a specific query with each GraphQL request, we can create one generic API call.
async function fetchAPI(query, {variables} = {}) {
const headers = {'Content-Type': 'application/json'};
const res = await fetch(API_URL, {
method: 'POST',
headers,
body: JSON.stringify({query, variables}),
});
const json = await res.json();
if (json.errors) {
console.log(json.errors);
throw new Error('Failed to fetch API');
}
return json.data;
}
Then we'll create a function to retrieve all posts by using the function above.
export async function getLatestPosts() {
const data = await fetchAPI(
`
query AllPosts {
posts(first: 10, where: { orderby: { field: DATE, order: DESC } }) {
edges {
node {
id
title
excerpt
featuredImage {
node {
sourceUrl
}
}
}
}
}
}
`
);
return data?.posts;
}
This function will use our fetchAPI function and pass a GraphQL query to it. This query will ask for ten posts ordered by date and fetch some specific fields.
The next step we need to do is call this data and render it on the homepage.
Let's use the getStaticProps again to fetch the data on build time.
import {getLatestPosts} from '../lib/api';
export async function getStaticProps() {
const latestPosts = await getLatestPosts();
return {
props: {latestPosts},
};
}
We call the getLatestPosts function on our lib/api.js file and return those posts as props.
Now we need to modify our Home function actually to retrieve these posts props.
export default function Home({latestPosts: {edges}}) {
// Render
}
Then we can wrap our existing elements into multiple ones bases on the posts and add the data.
{
edges.map((post) => (
<div
className="max-w-xs mx-2 my-2 overflow-hidden rounded shadow-lg"
key={post.node.id}
>
<img
className="w-full"
src={post.node.featuredImage?.node.sourceUrl}
alt={post.node.title}
/>
<div className="px-6 py-4">
<div className="mb-2 text-xl font-bold">{post.node.title}</div>
<div
className="text-base text-grey-darker"
dangerouslySetInnerHTML={{__html: post.node.excerpt}}
></div>
</div>
</div>
));
}
And with that, we now have our WordPress posts rendered on our homepage!

If you want a detailed view of the complete code, check out the GitHub repo.
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter