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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay