Headless WordPress Dynamic pages with GatsbyJS

In the last article of this series, I have shown “basics of headless WordPress with GatsbyJS”. Follow the previous article to start from the beginning.

Part One

In this article, I will show ‘how to create dynamic pages/routes with GatsbyJS’. I will fetch all post data from the WordPress website and create dynamic routes for each post.

Donald Trump GIF - Find & Share on GIPHY

At first, we need to create gatsby-node.js file in the root of our wp-gatsby project directory. Gatsby handles all dynamic routes from this file. Then add this asynchronous function in the file.

Here, I wrote a Graphql query to fetch post data from the WordPress website than on line 26 creating dynamic routes.

Behind the screen, Gatsby will create routes root-url/post-slug for each post, expect output from ./src/templates/post.js this file and Gatsby will also send each post data to this file.

So now let’s go ahead and create post.js file on the following path and add these pieces of code on the file…

import React from "react"

const Post = ({ pageContext: { post } }) => {
	return (
			<div dangerouslySetInnerHTML={{ __html: post.content }} />

export default Post

Now you can see the output on the browser, each post has a dynamic page. In my case the route is http://localhost:8000/post-slug-name.
You can create any dynamic route, following this procedure…

Easy Office Space GIF - Find & Share on GIPHY

Things are Hard, till you don’t go through it.

Said by ‘Easy’
Sandra Bullock Cheers GIF - Find & Share on GIPHY
Part Three
4.6 7 votes
Article Rating