How to Build a Website With Gatsby and WordPress (In 8 Steps)

By transitioning to a headless WordPress setup, you can have more control over your online content. However, building a front end for your website is also imperative. To do this, you can make a Gatsby WordPress site.

Using Gatsby, you can create a static version of your WordPress website. It can effectively improve your content delivery speed and overall site security. As a result, your website can experience better search rankings, user experience, and conversion rates.

In this post, we’ll explain what Gatsby is and the benefits of integrating it with WordPress. Then, we’ll show you how to build a WordPress Gatsby website. Let’s get started!

Download Website Launch Checklist

An Introduction to Gatsby

When you start using WordPress, you’ll build a dynamic website. Your server will generate a unique HTML file based on the request whenever someone visits your site.

Essentially, dynamic websites such as WordPress use browser-side rendering. Your web pages might load differently based on user behavior, time zone, or location.

Alternatively, you can create a static website. Using pre-built HTML, CSS, and JavaScript coding, static web pages will stay the same with every page load.

Converting your site into a static version is called a serverless or headless WordPress website. During this process, you’ll need to generate HTML pages for every piece of content on your site. To do this, you can use a static site generator like Gatsby.

Gatsby is an open-source static site generator based on React.JS, GraphQL, and Webpack. This framework enables you to create a static website with React and source data from your WordPress database.

Gatsby static site generator front page

Essentially, Gatsby will fetch data and render content from many different sources. These can include data from existing websites, API calls like REST, or flat files through GraphQL. Gatsby will then build your static site based on the configuration options.

Gatsby hasn’t been around as long as some other static site generators. However, it quickly rose to popularity and is now the preferred platform for many websites. One popular Gatsby example is Airbnb’s blog for engineers and data scientists.

Airbnb.io is a popular blog for engineers and data scientists

However, you may think WordPress is a more capable and effective content management system (CMS) than some of the other alternatives. To recognize if Gatsby is right for you, let’s discuss some of the static site generator’s pros, cons, and use cases.

Advantages of Using Gatsby

Page loading time is likely one of your primary concerns, whether you’re a website owner or developer. Since page speed can impact search rankings and user experience, you’ll want to find different ways to speed up your website.

One of Gatsby’s main benefits is its fast loading speeds. Static websites can typically process requests faster than dynamic ones. With Gatsby, you can quickly source, compile, and build content.

Gatsby offers deferred static generation, intelligent page rendering, and static site files. These performance optimizations can improve your page speed, SEO traffic, and conversion rate.

Static websites can also be more secure. When you have statically generated files, there will be fewer vulnerabilities. This level of security makes it difficult for hackers to exploit your site.

If you have a dynamic website, your server must be compatible with your technology stack. However, Gatsby static sites can be hosted on any server. Since you don’t need a specialized server, you can potentially find a more cost-effective hosting solution.

Gatsby Use Cases

In general, Gatsby can be a helpful tool for anyone who wants to build a static website. It’s often the best option for sites that don’t require frequent changes. However, let’s dive into some specific use cases to help you understand if Gatsby is the right choice for your site.

As we mentioned earlier, static websites are superior when it comes to speed. For eCommerce businesses, this is an essential factor to consider. Since Gatsby can decrease your page loading time, it is an effective option for optimizing conversion rate.

Gatsby offers over 2,500 plugins to easily build a website with the proper functionality. Whether your niche is in luxury goods, home decor, or clothing, you can create a Gatsby WordPress site with high-quality and interactive features.

Daniel Wellington is one excellent Gatsby-WordPress website example

Gatsby’s architecture doesn’t require a server or database. This setup can enable your site to handle a large amount of traffic. As long as your content delivery network (CDN) is functioning correctly, you shouldn’t experience any downtime.

As a content creator, you’ll likely want to include a number of photos on your website. Fortunately, Gatsby can optimize images for fast delivery. This optimization method avoids putting too much strain on your server resources.

Evie Magazine is one example of Gatsby's image optimization capability

Here are some more website niches that can benefit from using Gatsby:

  • Consumer finance and insurance
  • Public interest organizations
  • Web and WordPress development
  • Marketing
  • Software and SaaS

Ultimately, Gatsby is a flexible tool that can generate many different types of static websites. Regardless of the kind of content you create, Gatsby can effectively optimize the delivery of your files to maximize speed and user experience.

Downsides of Using Gatsby

Although Gatsby offers many benefits, it’s not for everyone. The platform is built on WordPress React, so you’ll need to be familiar with JavaScript. You’ll also have to use GraphQL to create and manipulate queries.

It’s also important to remember that Gatsby only serves static files. This means you’ll have to reconsider how to use dynamic content.

Often, dynamic content is a necessary part of your website. For example, you might want to display contact forms with custom fields. Also, you’ll likely want to encourage user engagement in the comments sections.

You will need to find a third-party service to serve these dynamic elements. For example, an external platform such as Google Forms can handle any contact form, or you can host comments with Disqus. However, with either of these options, you won’t be able to control your dynamic content directly.

Finally, you’ll face a delay whenever you edit an element on your static site. With a CMS such as WordPress, you can see any changes instantly. However, you’ll have to wait at least a minute with Gatsby because of the way it pre-renders content.

How Difficult Is Gatsby to Learn?

You may face a steep learning curve when you first use Gatsby as a beginner. Managing HTML, CSS, JavaScript, and the command line can be challenging if you’re new to WordPress development.

However, if you’re familiar with these basic WordPress development skills, you can easily learn Gatsby. This will involve managing React.js, which is a JavaScript library. If you can already write JavaScript, you will have an easier time during this process.

Additionally, you can style your Gatsby WordPress website with HTML and CSS. Since these coding languages are relatively easy to learn and use, Gatsby shouldn’t discourage you.

Gatsby also provides a lot of documentation and how-to tutorials. Even if you’re a beginner, you can quickly learn everything you need to create a static website with WordPress and Gatsby.

Furthermore, Gatsby is an open-source project, so developers constantly improve these resources.

How to Build a Website With WordPress and Gatsby (In 8 Steps)

Now it’s time to learn how to make a website with WordPress and Gatsby. Then you can serve your website as static files and easily improve loading time alongside an enriched user experience. Instead of using a WordPress Gatsby theme, we’ll show you how to do this process from scratch.

Step 1 – Create a WordPress Website

Using Gatsby, you can deliver your WordPress site as static content. To get started with this process, you’ll need to install WordPress, which will serve as the data source for Gatsby. This can be an existing website, a new installation, or a local environment.

You’ll first need to find a compatible web hosting service, as a hosting provider will provide the server space for your new website. During this process, you should be able to create a domain name and install WordPress all in one place.

Here at Hostinger, we provide some of the most cost-effective hosting plans available. If you’re looking for a high-quality WordPress-optimized server, you can’t go wrong with our WordPress hosting. Our plans start from as low as $1.99/month.

High-quality WordPress hosting service as provided by Hostinger

After purchasing a plan, you’ll need to choose a domain and install WordPress. By signing into your hPanel account, you can view the details of your plan.

Click on the Dashboard button. This will open your WordPress admin dashboard, which you’ll use to administrate the back-end of your website.

Step 2 – Install Gatsby Plugins

You’ll need to install and activate a few WordPress plugins for the next step. First, WPGraphQL is a free and open-source tool that will enable GraphQL API in WordPress. This plugin will set up WordPress as a data source and allow this data to be queried by GraphQL.

Head to Plugins -> Add New in your WordPress dashboard to install the plugin. Then, search for “WPGraphQL.” Once you have found the plugin, install and activate it.

Installing and activating the WPGraphQL WordPress plugin

The second plugin you’ll want to download is WPGatsby. This tool will keep your WordPress website synced with Gatsby. It can also let you override the WordPress preview and replace it with the Gatsby front-end.

After activating both of these plugins, go to GraphQL -> Settings. Here, find the GraphQL Endpoint.

GraphQL Endpoint option as shown in WordPress

You should see an endpoint path for the GraphQL API on your site. Since you’ll need this information later, be sure to copy the URL.

Before you get started with Gatsby, you might consider changing your WordPress permalink. To achieve the best results with WPGraphQL, you’ll need to avoid using the “plain” permalink structure.

You can update your permalink structure by selecting Settings -> Permalinks. Under Common Settings, choose any option other than Plain.

Changing the permalink settings on WordPress

Be sure to save your changes. After this, open the command line and test the connection between WordPress and GraphQL using this command:

curl --location --request POST 'https://your_domain/graphql' \
--header 'Content-Type: application/json' \
--data-raw '{
    "query": "query { posts { nodes { title } } }"
}'

This will send a request to the GraphQL endpoint of your website. You’ll receive a JSON response to the query listing your site’s post titles if it’s functioning correctly.

Step 3 – Install Gatsby

Before installing Gatsby, you’ll need to ensure you’re meeting its prerequisites. Since Gatsby is served through the node package manager (npm), you’ll need to install both NodeJS and npm. Additionally, Git will be necessary to manage code.

To download Git and NodeJS, you can use a package installer. For Mac users, start by installing Homebrew, a macOS missing package manager.

Homebrew missing package manager for macOS front page

In the command terminal, enter the following command to install and configure Homebrew:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 

Once Homebrew installs, you can use these commands to install both NodeJS and Git:

brew install nodejs
brew install git

If you have a Windows computer, head to the download pages for Git and NodeJS. Choose the Windows version and download both packages.

For Linux operating systems, you can use a package installer like apt. To install the necessary software, use these commands:

sudo apt update
sudo apt install nodejs git

Now you should meet the requirements needed to install Gatsby. To do this, run the following command in your software terminal:

npm install -g gatsby-cli

This will automatically run the Gatsby installer. You’ll notice that it will download and install all the necessary dependencies and then Gatsby itself.

Step 4 – Create a Gatsby Site

Once the Gatsby installation process is complete, you’ll be ready to build your first Gatsby WordPress website. To start, simply enter the following command:

gatsby new gatsby-site

This will clone the default starter template and put it under the /gatsby-site directory. Once finished, your Gatsby site will be bootstrapped. Then, you can open the development version with this command:

cd gatsby-site
gatsby develop

After this, the command terminal will tell you that you can visit your new local website. Open a web browser and visit http://localhost:8000/. This will allow you to view the Gatsby front-end of your site.

Gatsby local website example

You can start building your static site if you don’t see any errors. This process involves creating the files in the public directory. To do this automatically, enter the following command:

gatsby build

Lastly, you can start a local HTML server to display your new website. It’s important to note that this will only be successful after the build command has run:

gatsby serve

This will successfully set up a basic static Gatsby site.

Step 5 – Connect WordPress and Configure Gatsby

Now that you have a default static website, it’s time to integrate it with WordPress. For this step, you’ll direct Gatsby to the address of your WordPress site. This will pull the latest data from your website when you run this development server.

First, install the Gatsby WordPress plugin. You can do this by running the following command:

npm install gatsby-source-wordpress

Then, use your preferred text editor to open the gatsby-config.js file, which is the default configuration file for Gatsby. To connect Gatsby to a WordPress source, add this code:

module.exports = {
  siteMetadata: {
    ...
  },
  plugins: [
    ...
    {
        resolve: `gatsby-source-wordpress`,
        options: {
            // Specify the URL of the WordPress source
            baseUrl: `example.com`,
            protocol: `https`,
            // Indicates if a site is hosted on WordPress.com
            hostingWPCOM: false,
            // Specify which URL structures to fetch
            includedRoutes: [
              '**/posts',
              '**/tags',
              '**/categories'
            ]
        }
    }

Remember to replace “example.com” with the GraphQL endpoint you copied earlier. If you’re using a locally hosted site, you can use “localhost:8888/wordpress” to replace your site URL.

Step 6 – Customize the Default Template Files

When you install Gatsby, it will include a basic starter template. This contains a few basic source files with default functionality. To customize your website, it’s important to know about these essential template files:

  • ./gasby-node.js – contains the code for querying WordPress to pull your content, then generate the static output. By editing this file, you can modify the content displayed on your website. If you’re familiar with WordPress development, this process is similar to editing the Loop.
  • ./src/templates – individual template files that contain and export a React component. Since they are responsible for rendering content, these files play an essential role in changing your site’s appearance. They are similar to WordPress template files.
  • ./src/components – each file in this folder contains a React component that performs a specific UI task. Rather than templates, these are UI building blocks. You can paste the code into this folder if you want to share a UI element across multiple template files. In WordPress, these would be template partials.
  • ./src/css – consists of CSS files shared across the website, similar to the style.css file in WordPress.

Now that you understand how these files work, it’s time to add your customizations.

Display a Post Excerpt

On your WordPress site, your blog posts will have excerpts, which are summaries of each post. However, Gatsby will pull an excerpt primarily for search engine optimization (SEO) purposes. It will put the excerpt in the meta description.

You may want to customize how your blog posts are displayed on your static website. To do this, you can open the ./src/templates/blog-post.js file.

To start displaying blog post excerpts, add the highlighted code to your template file:

const BlogPostTemplate = ({ data: { previous, next, post } }) => {
	...
	return (
		<Layout>
			...
			<h1 itemProp="headline">{parse(post.title)}</h1>
      
			<p>{post.date}</p>

			{/* Checking for and adding the post excerpt if the current post has one*/}
			{post.excerpt && (
				<div className="post-excerpt">{parse(post.excerpt)}</div>
			)}

      {/* if we have a featured image for this post let's display it */}
        {featuredImage?.fluid && (
          <Image
            fluid={featuredImage.fluid}
              alt={featuredImage.alt}
              style={{ marginBottom: 50 }}
          />
        )}
      ...
		</Layout>
	)
}

Gatsby will now automatically check to see whether the post has an excerpt. If so, it will display it as text content inside an <div> element. Once you’re finished editing this file, save your changes.

Add Custom CSS

You may want to add visual effects while customizing your Gatsby site. With custom CSS, you can highlight certain elements on the page to make them easier to find.

For example, suppose you want to include a shadow effect around your post excerpt. To do this, you’ll need to open the ./src/css/style.css file in a text editor. Then, you can paste the following code to customize your box-shadow property:

.post-list-item header {
  margin-bottom: var(--spacing-4);
}

/* CSS targeting your new post excerpt element */
.post-excerpt {
  box-shadow: 0px 1px 9px 1px rgb(0 0 0 / 50%);
  padding: 6px;
  border-radius: 8px;
  margin-bottom: 14px;
}

.post-excerpt p {
  margin-bottom: 0px;
}

This code will create a shadow around the excerpt container, making it appear more engaging. You can also specify a unique level of padding, rounded edges, and spacing as well.

When you’re happy with your changes, save the file. Then, you can visit your Gatsby site to view the added effects.

Step 7 – Build a Page Template

In the previous step, you configured an existing template to render your blog posts as static Gatsby files. You can also create a basic template for every page on your WordPress Gatsby website. Once you code the design template, Gatsby will automatically generate a post for each of your WordPress pages.

To do this, you can use the createPage action. First, open the gatsby-node.js file and add this new code:

const path = require(`path`)
const { slash } = require(`gatsby-core-utils`)
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  // query content for WordPress posts
  const result = await graphql(`
    query {
      allWordpressPost {
        edges {
          node {
            id
            slug
          }
        }
      }
    }
  `)
  const postTemplate = path.resolve(`./src/templates/post.js`)
  result.data.allWordpressPost.edges.forEach(edge => {
    createPage({
      // will be the url for the page
      path: edge.node.slug,
      // specify the component template of your choice
      component: slash(postTemplate),
      // In the ^template's GraphQL query, 'id' will be available
      // as a GraphQL variable to query for this post's data.
      context: {
        id: edge.node.id,
      },
    })
  })
} 

This will effectively pull the data from GraphQL, generating a page for each WordPress post. Then, you can use the develop command to navigate to the new pages in Gatsby.

You can also create a directory template. You’ll need to open the templates folder and find the blog-post.js file. Here, add the following code:

import React from "react"
import Layout from "../components/layout"
import { graphql } from "gatsby"

export default ({ data }) => {
  const post = data.allWordpressPost.edges[0].node
  console.log(post)
  return (
    <Layout>
      <div>
        <h1>{post.title}</h1>
        <div dangerouslySetInnerHTML={{ __html: post.content }} />
        <p> By: {post.author.name} </p>
        <p> On: {post.date} </p>
      </div>
    </Layout>
  )
}

export const query = graphql`
  query($slug: String!) {
    allWordpressPost(filter: { slug: { eq: $slug } }) {
      edges {
        node {
          title
          content
          slug
          date(formatString: "MM-DD-YYYY")
          author {
            name
          }
        }
      }
    }
  }

When you need to add links to these new pages, head to the index.js file. Next, paste the following code:

import React from "react"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"
import SEO from "../components/seo"

export default ({ data }) => {
  return (
    <Layout>
      <SEO title="home" />
      <h1>My WordPress Blog</h1>
      <h4>Posts</h4>
      {data.allWordpressPost.edges.map(({ node }) => (
        <div>
          <Link to={node.slug}>
            <p>{node.title}</p>
          </Link>
          <div dangerouslySetInnerHTML={{ __html: node.excerpt }} />
        </div>
      ))}
    </Layout>
  )
}

export const pageQuery = graphql`
  query {
    allWordpressPost(sort: { fields: [date] }) {
      edges {
        node {
          title
          excerpt
          slug
        }
      }
    }
  }

When doing this, add links to each post within the code. After saving your changes, you’ll have an index page with links to all of your blog posts.

Step 8 – Perform Additional Migration Tasks

Once you successfully import all of your WordPress posts to Gatsby, you can start reaping the benefits of your new static site. However, you may want to consider completing a few extra precautions so that you avoid some future issues.

Store Images Locally

Although your posts might display correctly in Gatsby, the images could be pointing back to WordPress. In this case, you’ll want to enable images to be hosted on Gatsby. Remember that you won’t have this problem if you host images externally.

In Gatsby, you can avoid serving WordPress images with the Inline Images plugin. To install this tool, enter these two commands:

npm install gatsby-image
npm install gatsby-wordpress-inline-images

Next, open your gatsby-config.js file. Here, add the following code:

module.exports = {
  siteMetadata: {
    ...
  },
  plugins: [
    ...
    {
      resolve: `gatsby-source-wordpress`,
      options: {
        ...
        // If useACF is true, then the source plugin will try to import the WordPress ACF Plugin contents.
        // This feature is untested for sites hosted on WordPress.com
        useACF: true,
        plugins: [
          {
            resolve: `gatsby-wordpress-inline-images`,
            options:
            {
              baseUrl: `localhost:8888/wordpress`,
              protocol: `http`
            }
          }
        ]
      }
    }
  ],
}

After this, save your changes. Then, restart your development server, which will download your WordPress images and store them locally.

Display a Post’s Last Modified Date

Using GraphQL queries, you likely have already pulled the creation dates for your blog posts. However, you may also want to consider displaying a “last modified” timestamp as well. It can inform your readers that they’re reading up-to-date content.

Adding a “last modified” date to your Gatsby posts is straightforward. In a GraphQL query, insert this code into your blog-post.js file:

...
<Layout>
  <div>
    ...
    <p> On: {post.date} </p>
    <p> Last modified: {post.modified} </p>
  </div>
</Layout>
...

export const query = graphql`
  query($slug: String!) {
  {
    allWordpressPost {
      edges {
        node {
          ...
          modified(formatString: "MM-DD-YYYY")
        }
      }
    }
  }

This will update your blog post with a new “last modified” timestamp. Now your WordPress Gatsby website is ready to go!

Conclusion

With Gatsby, you can convert your WordPress website into static files. Although this setup requires JavaScript and GraphQL coding knowledge, Gatsby can offer more flexibility for securing and scaling your online content.

To recap, here’s how you can build a website with WordPress and Gatsby:

  1. Create a WordPress website.
  2. Install the Gatsby plugins WPGraphQL and WPGatsby.
  3. Install Gatsby.
  4. Create a Gatsby site.
  5. Connect WordPress and configure Gatsby.
  6. Customize the default template files.
  7. Build a page template.
  8. Perform additional migration tasks.

Now you should be fully prepared to transition your content into a WordPress Gatsby website!

Was this tutorial helpful?

Author
The author

Will M.

Will Morris is a staff writer at WordCandy. When he's not writing about WordPress, he likes to gig his stand-up comedy routine on the local circuit.