paint-brush
Configuring WordPress as Headless CMS using REST API with Nextjsby@dhavalveera
574 reads
574 reads

Configuring WordPress as Headless CMS using REST API with Nextjs

by Dhaval ViraJuly 25th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Hello Guys, in today’s blog, we are going to see how we can configure WordPress as Headless CMS using REST API with Nextjs. 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
featured image - Configuring WordPress as Headless CMS using REST API with Nextjs
Dhaval Vira HackerNoon profile picture

Hello Guys, in today’s blog, we are going to see how we can configure WordPress as Headless CMS using REST API with Nextjs.


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


I am assuming that you all know how to use Next.js, if you want to know & learn about Next.js, please Click Here.


To integrate/configure WordPress CMS into Next.js, we're going to use REST API which is made available by WordPress. Also, we're not going to use GraphQL. Before diving into this article, if you want to explore WordPress REST API Documentation, click here. And for this article. we'll be referring to this.


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.


Once you get the version number in the output, you can run the following command:

npx create-next-app wpDemo


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


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

cd wpDemo


and finally

npm run dev


or

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


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

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

Files to Edit

Open the /pages/index.js file and delete all the boilerplate code except:

<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.


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
      }
   }
}
export default function Home (props) {
    const { variableNameTwo, ...other } = props;
    return (
       <Head>...</Head>

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


or you can use useEffect() like below:

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 the 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 published.


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.

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


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.


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

data['title']['rendered']

The above syntax is used to retrieve the blog title.


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

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


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

To access the featured image from WordPress, use the above code snippet.


{data['date']}

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


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

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


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

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


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

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


That’s it for now!


Also published here.