Display WordPress page content in Gatsby page template components

Jason Lengstorf
InstructorJason Lengstorf
Share this video with your friends

Social Share Links

Send Tweet

To display WordPress page data like the title and content in a Gatsby component, we need to export a page query and use that data in our component. In this video, we write a Gatsby page query to load WordPress data, then write the JSX to display that content.

Jason Lengstorf: [0:01] To load each page, we're going to use its id. We can reference variables in WordPress by setting an id like this. We know that the id that comes in is going to be an ID and we're going to give it the name of id. Once we have that, we can get out of pages and instead go straight to page. We're going to set the page id to be id.

[0:25] Once we have that, we can get the title and the content which is what we're going to use. We're going to set a query variable. We're going to make that the id, lowercase. Then I'm going to pull this value for the home page and put that here.

[0:40] Once we have that, I can run this query and we see that we get back just the information about the home page, the title and the content which we'll be able to use in our Gatsby page. I'm going to copy this directly.

[0:55] We can take that into our page-template where I'm going to more or less paste it straight in. I'm going to get { graphql } from 'gatsby'. Then I'm going to export const query = graphql`. Inside, I'm going to drop this query.

[1:17] The id is going to come in from the context that we set in our gatsby-node.js, this context. Anything we set here gets created both as page context props on the component and also as a variable for GraphQL. We're going to use that id directly to make this request for the title and content.

[1:38] If we save this and go back out to our running site, we'll see that we get this new data prop and that it includes the wpgraphql page and then the title and content. We're able to use this now to style our page. Instead of doing this pre dump, we're going to switch to a fragment. Inside of it, we're going to use an <h1 />, and we're going to use a <div /> for the content.

[2:07] Because this comes back with HTML, we're going to use dangerouslySetInnerHTML. We're going to use for the title as well, because if our title did include any kind of special character, it would be HTML encoded.

[2:21] We're going to use dangerouslySetInnerHTML. I'm going to type both out at once to save time, dangerouslySetInnerHTML, and that gets an object with a key of __html. Get the data out. Then we'll do const page = data.wpgraphql.page. Then we can run with page.title and page.content.

[2:56] If we save that, and head out to check it out, we can see now that we're loading our WordPress pages into this Gatsby component.