Using Gatsby with the WordPress API

Install and setup

# install Gatsby
npm i -g gatsby-cli

# Disable sending usage stats to Gatsby, because i don't like sending stats even if anon
gatsby telemetry --disable

# Create new Gatsby project
gatsby new myProjectName && cd myProjectName

# install WordPress plugin
npm i gatsby-source-wordpress

# Open the project in VS Code
code .

# Start development server
gatsby develop

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


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


Configure Gastby plugin

module.exports = {
  // ...
  plugins: [
    // ...
        resolve: `gatsby-source-wordpress`,
        options: {
            // Your WordPress source.
            baseUrl: ``,
            protocol: `https`,
            // Only fetches posts, tags and categories from the baseUrl.
            includedRoutes: ['**/posts', '**/tags', '**/categories'],
            // Not using ACF so putting it off.
            useACF: false

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:

// gatsby-config.js
  path: `.env.${process.env.NODE_ENV}`

module.exports = {
    // ...
  auth: {
    jwt_user: process.env.JWT_USER,
    jwt_pass: process.env.JWT_PASSWORD,

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

import React from "react"
import { StaticQuery, graphql, Link } from "gatsby"

const Posts = ({ data }) => (
`query` from `graphql` only works at the page level
to use `graphql` inside components, you have to use the
<StaticQuery> component
    // The result of the query is automatically inserted into your React component on the data prop.
      query {
        allWordpressPost {
          edges {
            node {
    render={data => (

          { => {
            return <li>{post.node.title}</li>

export default Posts