Tutorial

Faster WordPress Sites With Gatsby

Published on December 12, 2019
author

Maedah Batool

Faster WordPress Sites With Gatsby

Talk about the latest cutting-edge web technologies, and you find some impressive names like React.js, Vue.js, Next.js, and so on. They have opened new gateways and approaches to building websites that can serve content to users quickly.

One framework that can increase overall site speed and load times is Gatsby.js.

Goals of a Fast Website

A website that loads fast entails the following perks and benefits for developers:

  • Traffic and Engagement: You get more site visitors on a fast site, which translates to better ROI and user engagement.
  • Page Ranks: Fast websites earn higher browser rankings.

Improving Site Speed With Gatsby.js and WordPress

Gatsby.js is a free and open-source React.js-based framework that helps developers build websites and applications. It is part of a general trend toward JAMstack (JavaScript APIs Markup) sites, which aim to increase overall site speed and load times.

But where does Gatsby fit with WordPress, one of the most widely-used CMS options available today? Despite its usability and robust community, WordPress can pose challenges to building a modern frontend, for the following reasons:

  • Updates and Changes: WordPress is regularly updated, but it still lacks parity with other rapidly-changing front-end technologies. Staying up-to-date with these technologies adds an additional burden for the developer.
  • Continuous Integration and Deployment: Right now, few Continuous Integration/Deployment (CI/CD) options exist in the WordPress ecosystem.
  • Integration Costs: It can be challenging to integrate some of the latest front-end technologies with a WordPress application.

Using Gatsby can address some of these limitations. In the following steps, we will show you how to integrate Gatsby with WordPress to take full advantage of both. First, we are going to configure a basic Gatsby project setup. Then, we’ll use it to fetch data from our WordPress site.

Integrating Gatsby.js with WordPress

First, we will set up a demo Gatsby project.

Install the Gatsby CLI by typing the following command in your terminal:

  1. npm install -g gatsby-cli

Next, create a new Gatsby site with the following command:

  1. gatsby new site-name

To access your site folder contents, type the following:

  1. cd site-name

Finally, start the development server to begin building your site:

  1. gatsby develop

Installing the gatsby-source-wordpress Plugin

Assuming that you have a WordPress site already set up, and you would like to have a frontend built with Gatsby.js, all you need to do is pull your existing site data into your static Gatsby site. You can do that with the gatsby-source-wordpress plugin.

This tutorial uses the default WordPress REST API site, though you are free to use a pre-existing WordPress setup if you have one.

Inside your terminal, type the following to install this plugin:

  1. npm install gatsby-source-wordpress

Configuring the Plugin

Inside your gatsby-config.js file, the main Gatsby configuration file, you will add some WordPress-specific configuration options. These include your WordPress site’s baseUrl, the preferred HTTP protocol, and settings pertaining to the Advanced Custom Fields (ACF) plugin. The includedRoutes fields specifies the data we want to fetch.

Using the demo WordPress site from the step above, the current frontend looks like this:

For the purposes of this tutorial, add the following code to a file called gatsby-config.js:

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

Using Fetched WordPress Data

Once your Gatsby site is fetching data from your WordPress source URL, it’s time to create your site pages. This is done by implementing the createPages API in the gatsby-node.jsfile, which makes the fetched data available to queries from GraphQL. At build time, the gatsby-source-wordpress plugin fetches your data, and uses it to ”automatically infer a GraphQL schema” which you can query against.

Add the following code to a file called gatsby-node.js:

/**
 * Implement Gatsby's Node APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/node-apis/
 */

// You can delete this file if you're not using it

const path = require(`path`);
const slash = require(`slash`);

/** STEP #1: Implement the Gatsby API “createPages”. This is
 * called after the Gatsby bootstrap is finished so you have
 * access to any information necessary to programmatically
 * create pages.
 * Will create pages for WordPress pages (route : /{slug})
 * Will create pages for WordPress posts (route : /post/{slug})
 */
exports.createPages = async ({ graphql, actions }) => {
	const { createPage } = actions;

	// STEP #2: Query all WordPress Posts Data.
	/** The “graphql” function allows us to run arbitrary
	 * queries against the local Gatsby GraphQL schema. Think of
	 * it like the site has a built-in database constructed
	 * 	from the fetched data that you can run queries against.
	 */
	const result = await graphql(`
		{
			allWordpressPost {
				edges {
					node {
						id
						slug
						status
						template
						format
					}
				}
			}
		}
	`);

	// Check for any errors
	if (result.errors) {
		throw new Error(result.errors);
	}

	// Access query results via object destructuring.
	const { allWordpressPost } = result.data;

	const postTemplate = path.resolve(`./src/templates/post.js`);

	// STEP #3: Create pages in Gatsby with WordPress Posts Data.
	/**
	 * We want to create a detailed page for each
	 * post node. We'll just use the WordPress Slug for the slug.
	 * The Post ID is prefixed with 'POST_'
	 */
	allWordpressPost.edges.forEach(edge => {
		createPage({
			path: `/${edge.node.slug}/`,
			component: slash(postTemplate),
			context: {
				id: edge.node.id
			}
		});
	});
};

This will iterate through existing WordPress post data.

Step #4: Creating a post.js Template

Next, we will create a folder for templates, where you can add files for posts, pages, and layouts. For now, we will create a post.js file to fetch posts from our WordPress site.

Add the following code to the file:

import { graphql } from 'gatsby';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Layout from '../layouts';

class PostTemplate extends Component {
	render() {
		const post = this.props.data.wordpressPost;

		// STEP #5: Use title and content in Gatsby.
		return (
			<Layout>
				<h1 dangerouslySetInnerHTML={{ __html: post.title }} />
				<div dangerouslySetInnerHTML={{ __html: post.content }} />
			</Layout>
		);
	}
}

PostTemplate.propTypes = {
	data: PropTypes.object.isRequired,
	edges: PropTypes.array
};

export default PostTemplate;

// STEP #4: Get current WP Post data via ID.
export const pageQuery = graphql`
	query($id: String!) {
		wordpressPost(id: { eq: $id }) {
			title
			content
		}
	}
`;

Examining the Final Result

To start the development server and view the final result, type the following command in your terminal:

  1. npm start

You will get the link where you can access the site locally, along with other details like the number of posts, categories, and tags that are being fetched.

Here’s a GIF that demonstrates what this will look like:

Let’s take a look at this revamped front-end which is now powered with Gatsby.js and a WordPress back-end:

You can see how our application is only fetching the required data from the WordPress site. This includes posts, tags and categories. To retrieve other types of data like widgets or comments, you will need to add the appropriate values to the includedRoutes option.

Conclusion

By following this tutorial, you now have a WordPress application backend integrated with a Gatsby.js frontend. Gatsby provides a fast web experience and brings with it added benefits that can enhance your existing WordPress site. You now have a platform for further experimentation with using Gatsby to power your site,

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Maedah Batool

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.