DEV Community

Keramot UL Islam
Keramot UL Islam

Posted on • Originally published at blog.abmsourav.com

Headless WordPress Dynamic pages with GatsbyJS

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.

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.

exports.createPages = async ({ graphql, actions }) => {
    const { createPage } = actions

    const wpData = await graphql(`
        {
            allWordpressPost {
                nodes {
                    wordpress_id
                    slug
                    title
                    content
                    author {
                        name
                    }
                }
            }
        }
  `)

    if (wpData.errors) {
        console.error(wpData.errors)
    }

    const { allWordpressPost } = wpData.data
    allWordpressPost.nodes.forEach( post => {
        createPage({
            path: `/${post.slug}`,
            component: require.resolve(`./src/templates/post.js`),
            context: { post },
        })
    })

}
Enter fullscreen mode Exit fullscreen mode

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 to the file…

Read the original full article on my blog

This article is a part of my Headless WP series

Top comments (0)