How to configure WordPress in Nextjs using REST API
Tags: nextjs, restapi, wordpress
Published: 2022-11-27 08:49:11

Hello Guys, today in this blog we are going to explore & see how we can configure WordPress as Headless CMS using REST API with [Nextjs](https://www.nextjs.org/). This is going to be a long post, please bear with me,

As we move through future articles in the series, we'll be covering a lot of moving parts to round out the entire process, including:


- starting a Blog using a Next.js
- using WordPress as a Headless CMS (REST API) using Next.js

 
here, I am assuming that you all know how to use Next.js, if you want to know & learn about Next.js, please [Click Here](https://www.nextjs.org)


to integrate/configure WordPress CMS into Next.js, we're going to use REST API which is made available by [WordPress](https://www.wordpress.org), and here we're not going to use GraphQL


before exploring this article/blog, if you wanted to explore WordPress REST API Documentations, [click here](https://developer.wordpress.org/rest-api/), and for this article/blog we're going to use [this](https://developer.wordpress.org/rest-api/reference/posts/).

before running the below command, please make sure that the latest version of Node.js is installed (v16+) and also confirm that `create-next-app` is also installed and which can be confirmed by running `create-next-app -V` in the Terminal for Mac/Linux & cmd for Windows, and once you get the version number in the output, you can run the following command:

```bash
npx create-next-app wpDemo
```

Once finished, you'll receive a message saying everything has been successful and then you can give a few commands to build, run and start our new app.

Let’s check everything’s working first by typing the following commands in your terminal:

```bash
cd wpDemo
```

and finally

```bash
npm run dev
```

or 

```bash
yarn dev
```

What you'll see is a blazing fast site build, followed by a message that your site has successfully been started at `http://localhost:3000`. Open that address in a browser of your choosing and you should see the following page.

![Nextjs Welcome Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nuovvin9n2n3ug954qbx.png)

if you get this page means you have successfully built the Next.js website

we are going to fetch the Posts from WordPress using the `fetch()` method.



## Files to Edit

now open the `/pages/index.js` file and delete all the boilerplate code except:
```html
<Head></Head>
```

now we will call the WordPress REST API in order to fetch the Blog Posts from WordPress.



here we can use `useEffect()` to fetch the WordPress Blog Posts, but we'll use the feature & advantages of Next.js which helps for better SEO, so we'll use `getServerSideProps()`, and also note that `getServerSideProps()` can only be used with page-based files only not with components.


```js
export const getServerSideProps = async () => {
   const variableName = await fetch('https://your-wp-domain-url.com/wp-json/wp/v2/posts?_embed&order=desc&per_page=100&status=publish')
   const variableNameTwo = await variableName.json()

   return {
      props: {
         variableNameTwo
      }
   }
}
```

```js
export default function Home (props) {
    const { variableNameTwo, ...other } = props;
    return (
       <Head>...</Head>

       <ComponentName {...other} variableNameTwo={variableNameTwo} />
    )
}
```

or you can use `useEffect()` like below:

```js
const PageName = () => {
const [ variableNameTwo, setVariableNameTwo] = useState([]);

useEffect(() => {
		setLoading(true);
		const fetchBlogData = async () => {
			const blgData = await fetch(
				'https://your-wp-domain-url.com/wp-json/wp/v2/posts?_embed&order=desc&status=publish'
			);
			const blgJsnData = await blgData.json();
			setBlogData(blgJsnData);
			setLoading(false);
		};

		fetchBlogData();
	}, []);

    return (

         <ComponentName variableNameTwo={variableNameTwo} />

    )
}

export default PageName;
```

here, variableNameTwo will be an array that will contain all the post data.

let me describe/explain to you what parameters I’ve passed along with the URL to get the blog posts from WordPress.

1. **_embed**: this parameter is used to retrieve the featured images, Author Details, tags, categories, etc. along with the blog post.
2. **order**: we can retrieve the Blog posts based on ascending/descending order, by default it’s in desc order.
3. **per_page**: we can define how many posts we need to retrieve in 1 page, by default it’s 10, and the maximum number of posts per page is **100**.
4. **status**: it is used to retrieve the blog posts based on status, e.g. publish or draft, by default it’s **publish**.

for more parameters we can pass with posts, please refer [here](https://developer.wordpress.org/rest-api/reference/posts/)



now in componentName, you can iterate on the array and display the required blog data as per your design. and to open the particular single blog on the new page below is the code snippet.

```js
<Link href={`/blog/${mapName['slug']}`} passHref>
   <a className={styles.className}>
      Read More
   </a>
</Link>
```

now when you click on the Read More button/link, a new page will open with a particular/single blog post, we have to run the below code snippet in order to get the particular/single blog post details.

```js
export const getServerSideProps = async (context) => {
	const { slug } = context.params;

	const variableName = await fetch(`https://your-wordpress-website-url/wp-json/wp/v2/posts?_embed&slug=${slug}`);
	const variableNameTwo = await variabeName.json();

	if (variableNameTwo.length === 0) {
		return {
			redirect : {
				destination : '/404',
				permanent   : false
			}
		};
	}

	return {
		props : {
			variableNameTwo
		}
	};
};
```

now you can access the variableNameTwo, inside the page as props, and remember that variableNameTwo will be an array.

below are the code snippets which is used to retrieve the title, description, image, and slug

```html
data['title']['rendered']
```

above syntax is used to retrieve/get the blog title

```html
<div 
     dangerouslySetInnerHTML={{ __html: data['content']['rendered'] }}
/>
```

the above code snippet will display the blog content (e.g. description) on the page UI.

```html
<img
     src={data['_embedded']['wp:featuredmedia'][0]['source_url']}
	 alt={data['title']['rendered']}
/>
```

to access the featured image from WordPress, it can be accessed with the above code snippet.

```js
{data['date']}
```

with the above code snippet, you can get the date when the blog post was published.

```js
{data['_embedded']['author'][0]['name']}
```

with the above code snippet, you can get the name of the author, who wrote this blog post.

```js
{data['_embedded']['wp:term'][0][0]['name']}
```

with the above code snippet, you can get the name of the category.

```js
{data['_embedded']['wp:term'][1].map((tag) => {
	return (
		<Fragment key={tag['name']}>
			<p>{tag['name']}</p>
		</Fragment>
	);
})}
```

with the above code snippet, you have to iterate/loop on the `[‘wp:term’][1]`  in order to get all the tags.

to know more about me or want to read relevant & more blogs, find me at [my website](https://dhavalvira.com)