Search code examples
wordpressgraphqlgatsby

Wordpress Gatsby get parent props


I'm a grapql newby and struggling to get the parent props from current page. In gatsby-node.js I create all wordpress pages with:

createPage({
          path: `${page.node.uri}`,
          component: PageTemplate,
          context: {
            id: page.node.id,
            title: page.node.title,
            parentId: page.node.parentId
          },
        })

Then on the page I use following to get data from current page with:

query($id: String!) {
    wpPage(id: {eq: $id}) {
      id
      title
      uri
      content
      parentId
    }
  }

What I need is getting the parent props IF the page has a parentId, any suggestions? Thanks in advance!


Solution

  • To access the parent props if the page has a parentId in Gatsby with GraphQL, you can modify your query to fetch the parent page data using the parentId. Here's how you can do it:

    query($id: String!, $parentId: String) {
      wpPage(id: {eq: $id}) {
        id
        title
        uri
        content
        parentId
      }
      parentPage: wpPage(id: {eq: $parentId}) {
        id
        title
        uri
        content
        parentId
      }
    }
    

    In this query, we're fetching data for the current page using the provided $id. Additionally, we're fetching the parentPage data based on the parentId if it exists. This way, you'll have access to both the current page data and its parent page data, if applicable, in your GraphQL response.