Notes

Using Gatsby with the WordPress API

Edit on GitHub

JavaScript
2 minutes

Install and setup

 1# install Gatsby
 2npm i -g gatsby-cli
 3
 4# Disable sending usage stats to Gatsby, because i don't like sending stats even if anon
 5gatsby telemetry --disable
 6
 7# Create new Gatsby project
 8gatsby new myProjectName && cd myProjectName
 9
10# install WordPress plugin
11npm i gatsby-source-wordpress
12
13# Open the project in VS Code
14code .
15
16# Start development server
17gatsby develop

You can now view gatsby-starter-default in the browser.

http://localhost:8000/

View GraphiQL, an in-browser IDE, to explore your site’s data and schema

http://localhost:8000/___graphql

Configure Gastby plugin

 1module.exports = {
 2  // ...
 3  plugins: [
 4    // ...
 5    {
 6        resolve: `gatsby-source-wordpress`,
 7        options: {
 8            // Your WordPress source.
 9            baseUrl: `demo.wp-api.org`,
10            protocol: `https`,
11            // Only fetches posts, tags and categories from the baseUrl.
12            includedRoutes: ['**/posts', '**/tags', '**/categories'],
13            // Not using ACF so putting it off.
14            useACF: false
15        }
16    },
17  ],
18}

Environment variables

dotenv is already a dependency of Gatsby so you don’t need to install it. You can use it in gatsby-config.js or gatsby-node.js like so:

1// gatsby-config.js
2require("dotenv").config({
3  path: `.env.${process.env.NODE_ENV}`
4});
1require("dotenv").config()
2
3module.exports = {
4	// ...
5  auth: {
6    jwt_user: process.env.JWT_USER,
7    jwt_pass: process.env.JWT_PASSWORD,
8  }
9}

Querying data with GraphQL

You need to use the <StaticQuery> component in order to use GraphQL inside a component (as opposed to a page, for tyhat you use a page query). The main difference is that page queries can accept variables while StaticQuery does not.

The StaticQuery takes two

 1import React from "react"
 2import { StaticQuery, graphql, Link } from "gatsby"
 3
 4const Posts = ({ data }) => (
 5  /*
 6`query` from `graphql` only works at the page level
 7to use `graphql` inside components, you have to use the
 8<StaticQuery> component
 9*/
10  <StaticQuery
11    // The result of the query is automatically inserted into your React component on the data prop.
12    query={graphql`
13      query {
14        allWordpressPost {
15          edges {
16            node {
17              id
18              slug
19              title
20              content
21              excerpt
22              date
23              modified
24            }
25          }
26        }
27      }
28    `}
29    render={data => (
30      <div>
31        <h1>Posts</h1>
32
33        <ul>
34          {data.allWordpressPost.edges.map(post => {
35            return <li>{post.node.title}</li>
36          })}
37        </ul>
38      </div>
39    )}
40  />
41)
42
43export default Posts