Install and configure `gatsby-source-graphql` to read WordPress data from WPGraphQL

Jason Lengstorf
InstructorJason Lengstorf

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 2 years ago

Because WPGraphQL already provides a GraphQL API, we can access it directly in Gatsby using gatsby-source-graphql. In this video, we’ll install and configure the plugin in Gatsby so we can see WordPress data loaded in Gatsby’s data layer.

Jason Lengstorf: [0:00] Because we're using WPGraphQL, we need to be able to load an external GraphQL data source into Gatsby. We're going to use gatsby-source-graphql. To add that, we're going to jump into the terminal again.

[0:13] We're going to npm install gatsby-source-graphql. While we wait for that to download, we can go ahead and start to configure it. In gatsby-config.js, we're going to add a plugins array to our configuration and inside of it we'll add an object.

[0:33] It's going to resolve to gatsby-source-graphql which is the name of our plug-in. Then we're going to pass in options. This plug-in takes three options that we need to use. There are others, but we only need these three.

[0:47] We're going to set a typeName, which is what the field is going to be called inside of GraphQL. We're going to set it to WPGraphQL. It needs a field name. This is what we're going to query, so we'll just make that wpgraphql all lower case. Finally, we need to tell it where to get the data. Now, this is going to be your WordPress site, but it can be wherever your site lives.

[1:12] I'm going to use this wordpressjamstack demo site, but you can use yours if you would like to follow along. It's whatever the site's URL is, and then /graphqL at the end. Check that it's working. Let's start up the site by running npm run develop. This will start up Gatsby's development server and get it running on a local port so that we can try things out.

[1:42] Because we're not building anything yet, we're just going to use GraphQL. We're going to grab this GraphQL URL, head over to our browser. We'll see it graphical here. Then we can head down and we see WPGraphQL. Let's just grab our pages. We'll go to pages, nodes. Let's get the title, uri, and the content.

[2:08] This is the page data from WordPress, so we are in business.