Now let’s go back to our Gatsby site and get it hooked up to our WordPress site, and pull in some blog posts!
Open up gatsby-config.js in your text editor.
First I’m going to edit the
siteMetadata from the defaults to make the site my own:
There are so many great Gatsby plugins, but for the sake of this tutorial, we’ll only install what we need to connect WordPress.
npm install gatsby-source-wordpress-experimental
Next, we’ll go back and edit our gatsby-config.js file and add a .env file to the project. It will be ignored by gitignore.
Here’s what we’ll add to gatsby-config:
Make sure you add your WordPress site’s graphql link:
Next, we’ll need to edit the gatsby-node.js file. I followed what was in the docs and used:
Now our site is hooked up to our WordPress site, but there’s no real way to verify and view anything. So we’ll need to create a blog post template so we can pull in the information.
So with these new changes, we’re able to pull in the blog posts from our WordPress site and display them. Run
gatsby develop to check it out.
When the site loads we won’t see any differences on the home page. We haven’t set up our routes yet. If you go to a URL like this: http://localhost:8000/oops you’ll see a list of all the pages, and should see some of your posts from WordPress:
See those “fake” posts? Those are coming from WordPress!
It’s just pulling in the Title and Content, which we set up in our blog-post.js file.
Let’s add the date to our posts. If you go to your GraphQL locally, http://localhost:8000/___graphql you can see all the options of what we can pull in from a WordPress blog post:
Awesome! Next, we’ll create a page that will list out all of our blog posts.
This will be a list of published posts, to do this we’ll use a map function so we don’t have to worry about updating the page whenever future posts are published.
With these few lines, take a look at http://localhost:8000/blog/ and see what is there:
Click on the links to make sure they’re working. Now lets clean this up a little and get rid of the bullets.
For simplicity sake, we’ll create a new CSS file in the component folder named
style.css and add:
Finally, let's add a link to this page on the home page. I just added this line:
<Link to="/blog">Like this blog</Link>