WordPress is a popular CMS (Content Management System) which creates mostly dynamic websites. Almost 40% of the entire web is powered by this platform, which says a lot about it’s popularity. Gatsby JS, on the other hand, is a static site generator built with React JS and powered by GraphQL. Gatsby allows anyone to create feature-rich, engaging websites and applications. Gatsby fetches data for your site from a variety of sources including existing websites, API calls and flat files through GraphQL, and builds the static site based on configuration settings specified by you.
It is possible to create a static version of a WordPress website using Gatsby JS or some other similar platform such as Next JS. There are a few use cases where it might be better to use a static site generator and some in which it might not.
Benefits
- Built with performance in mind – Gatsby sites are 2-3 times faster than similar types of sites. It prefetches resources so clicking through your pages feels excitingly fast. Load times also affect page views and conversions. It has been estimated that a one-second delay in site load time can lead to 7% reduction in conversions.
- Security – Static site generators already have some built in features for protection against hacker attacks and also have some pretty easy ways to deal with security.
- Easier to maintain – given the development principles it is based on, it is generally easier for developers to maintain code
Downsides
- No Dynamic Content Built-In: In cases where dynamic content has to be served such as comments or contact forms it might be needed to use some third party app and integrate it.
- E-shops – As I’ve already hinted in the previous paragraph, the more content you have, the larger the build time with Gatsby, which is when this solution could slow you down rather than speed you up.
- Web apps – While technically it is possible to use Gatsby to create a standard web app, this framework is mostly suited for static presentation sites, blogs, e-shops, etc.
Step 1: Installing Gatsby
Prerequisites
Gatsby installation requires you to have Node JS installed on your computer so that you could install it using it’s package manager – npm. You can follow these instructions for installation. Additionally, you will need to install Git.
Install Gatsby
Once you have installed Node and npm, open up your terminal and type in the following command:
npm install gatsby
Build and Deploy Your Gatsby Site
Run the following command to install a Gatsby website.
gatsby new my-gatsby-project https://github.com/GatsbyCentral/gatsby-starter-wordpress
A new directory is created under the name of gatsby-starter-wordpress-blog. If you wish, you could install a different template which can be found on the official website. After that, you should go to that directory and using the following command start the website in development mode
cd gatsby-wordpress
gatsby develop
Development version of the site is created under http://localhost:8000. After you are finished creating your website you can run the build command so the static files can be created in the public directory. To upload it to the server, simply upload he contents of this directory to your server’s root directory.
Step 2 — Installing and Configuring the Required WordPress Plugins
On your fresh WordPress installation, navigate to Appearance -> Plugins. Next, navigate to the plugin installation page by clicking Add New at the top of the page, or in the same sidebar.
The two required plugins are as follows and should be installed in this order:
- WPGraphQL: this enables WordPress data to be queried by the GraphQL standard, as an alternative to WordPress’s standard REST endpoints. This is important because Gatsby uses GraphQL by default.
- WPGatsby: this plugin enables your WordPress installation to work as a data source for Gatsby. It allows your WordPress site to be in sync with Gatsby and provides some additional settings.
Install and activate both of these plugins by searching for them and then pressing their associated Install Now buttons. Once they are installed, select the Activate button.
To verify that the GraphQL connection will be available for connecting to Gatsby, open the Settings panel, under the GraphQL sub-section in the Admin sidebar.
The GraphQL endpoint shown here will be used later, so take some time to save it somewhere in your notes.
For the best results, it is recommended to refresh WordPress permalinks by setting it to something other than plain.
Step 3 – Connecting WordPress and Gatsby
Next step is to install the gatsby-source-wordpress plugin for Gatsby if it is not already installed. Then, open the file named ./gatsby-config.js in your text editor of choice. This is the main configuration file for all Gatsby projects. Copy and paste the following code and replace the url endpoint with the one you copied before.
module.exports = {
plugins: [
{
resolve: `gatsby-source-wordpress`,
options: {
url:
process.env.WPGRAPHQL_URL ||
`https://your_domain/graphql`,
},
},
…
],
…
}
After that, navigate to your local development site and you will see your recent post submissions to WordPress as follows:
Step 4 — Customizing the Starter Template Files
For most Gatsby websites, there are a few key files and folders to be aware of when it comes to customization:
- ./gatsby-node.js – It has the code for querying WordPress for all your content, then passing it through template files to generate the static output. If you want to modify what content ends up on your site, this is the main entry-point.
- ./src/templates – This contains individual template files, each of which should contain and export a React component responsible for rendering the content passed in. If you want to change how content looks, integrate third-party UI libraries, or build skeletons around content, this is the usual place to do it.
- ./src/components – If you have a UI element that you want to share across multiple template files, this is a good place to put it and avoid copying and pasting the same code over and over. Some examples of this would be menus, author bio displays, header and footer elements, etc.
- ./src/css – This contains CSS files that are shared across the site, as opposed to inline-styling, or a popular css-in-js solution, such as styled-components.
Step 5 — Using WordPress Data in Gatsby
In this next example you will see how to query display WordPress pages using a template and also include a menu in a navigation component. First of all, create a template files called page.js in the templates folder. Create a simple component which will be updated later, like so:
import React from “react”
import { graphql } from “gatsby”
import Layout from “../components/layout.js”
import SEO from “../components/seo”
const PageTemplate = () => (
<Layout>
<SEO />
PageTemplate
</Layout>
)
export default PageTemplate
After you have created this file you can start working on implementing a connection between WordPress pages and this template in gatsby-node.js. Using the createPage API you are creating pages based on a GraphQL query and telling it which template to use. Simply paste this code into the file:
async function createPagesTemplate({ graphql, actions, reporter }) {
const { createPage } = actions
const PageTemplate = path.resolve("./src/templates/page.js")
const result = await graphql(`
{
allWpPage {
edges {
node {
slug
id
}
}
}
}
`)
const Pages = result.data.allWpPage.edges
Pages.forEach(page => {
createPage({
path: `/${page.node.slug}`,
component: PageTemplate,
context: {
id: page.node.id,
},
})
})
}
After that, you will navigate to the page.js in the templates folder and paste the following code:
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout.js"
import SEO from "../components/seo"
const PageTemplate = ({ data }) => (
<Layout>
<SEO
title={data.wpPage.title}
description={data.wpPage.excerpt}
/>
<h1>{data.wpPage.title}</h1>
<div dangerouslySetInnerHTML={{ __html: data.wpPage.content }} />
</Layout>
)
export default PageTemplate
export const query = graphql`
query($id: String!) {
wpPage(id: { eq: $id }) {
title
content
}
}
`
Essentially, all you are displaying is the title and the content retrieved from the GraphQL query. To test out queries and see if they work navigate to the following link:
http://localhost:8001/___graphql
After you have finished building type out a page link you created in WordPress in your browser like so:
http://localhost:8001/sample-page
And you will see something like this:
Building a navigation component
To create a navigation component and inject WordPress data in it, you will be using a StaticQuery or in this case, a useStaticQuery hook. Before creating this file be sure to create a menu in your WordPress installation in Appearance->Menus like so:
In the components folder create a file called nav.js and paste the following code inside it:
import React from 'react'
import { Link, useStaticQuery, graphql } from "gatsby"
const Nav = () => {
const pageMenu = useStaticQuery(graphql`
{
allWpMenuItem(filter: {menu: {node: {name: {eq: "Primary"}}}}) {
edges {
node {
label
url
}
}
}
}
`)
return(
<div>
<ul style={{ listStyle: `none`, display: `flex`, margin: 0 }}>
{pageMenu.allWpMenuItem.edges.map(item => (
<li key={item.node.url} style={{ margin: `0 10px` }}>
<Link
to={`${item.node.url}`}
style={{
color: `black`,
textDecoration: `none`,
fontFamily: `sans-serif`,
}}
>
{item.node.label}
</Link>
</li>
))}
</ul>
</div>
)
}
export default Nav
Using this hook, we are querying all menu items based on menu name which we added in WordPress. To see this newly created menu include in your the blog-post-archive.js template by first import using the import statement:
import Nav from '../components/nav'
And then calling it where you want it displayed, like this:
<Nav />
Go to home page in your Gatsby application and you should see something like the following screen:
By clicking on the links in the menu you should be able to see the content and the title from these pages!
Conclusion
By working through the steps in this tutorial, you now have a statically generated Gatsby site that sources its content from a WordPress website. By decoupling content from UI, you have opened up new possibilities for speeding up your site. There is a lot more custom functionality that can be added such as inserting custom post types, galleries and so on!