In this article, we are building a Blog with Gatsby and WordPress API’s. We are using graphql for fetching data from the WordPress backend.
Let’s go step by step, first, we need to understand why we need Gatsby and what is it. WordPress itself is a very good platform for blogging then why we should use Gatsby static pages for the front look of the blog?
What is Gatsby?
Gatsby is a free, open-source static site generator that uses React. So with basic knowledge of React.js, you can start working on Gatsby.
Static sites are basically composed pages of HTML, CSS, and Javascript files.
Gatsby is a static site generator, and it is a very good alternative to traditional data-driven Content Management Systems (CMS) like WordPress.
So, when we open a WordPress website, it sends a request to the server for a particular URL that was requested by the user, then the server access the content from the database, This content is basically HTML content stored in the database, and the server generates these HTML pages as its response.
Now, This on-demand page generation can be very time taking and that’s where Gatsby plays an important role to resolve the issue of on-demand page generation from the database.
Gatsby creates these pages during the build process and stores all the data in JSON files and accesses the compose pages of HTML, CSS, and Javascript.
You can simply deploy these pages on the server and use them without any database connection and by this you can avoid unnecessary server request to the database which basically increase your website loading time.
Now you must be thinking, it’s good for content to display, but what if I need a contact form or I need a subscription box, these things are not static right, what do we do in these cases when we want some dynamic feature?
Well, these features you can simply create by using React.js. You can create dynamic forms like any React.js application have and you can use it inside the Gatsby Framework.
Also, one more question people usually ask me is that these pages are static, so whenever we do a simple change we need to go through a process of rebuilding the whole application and then uploading it to the server, don’t you think this is a very lengthy process?
I agree, and Gatsby has a solution for this, which is one of the best advantages of using a static site generator.
You can simply use GitHub and Webhooks.
You can create a webhook inside Github and one inside your WordPress backend and server. Now, whenever you push the code to Github, it will automatically request the server to generate a build for changes you made inside your code.
Now let’s start building our Gatsby blog by accessing WordPress API.
Build a Blog containing Pages, Posts, Categories, and Tags with Gatsby and WordPress
First of all, you have to install node js in your system, you can download it from here https://nodejs.org/en now you need to install Gatsby globally on your local machine, and for that, you can run this command inside a terminal like Git Bash and PowerShell.
npm i -g gatsby-cli
Gatsby is a Framework, it has its own Command Line Interface (CLI).
Now to create a new Gatsby project you need to run this command.
gatsby new wordpress-blog-frontend
cd wordpress-blog-frontend
Here wordpress-blog-frontend is my project name and with the cd wordpress-blog-frontend you can move inside the project directory.
Open this project inside your favorite code editor, mine is visual studio code.
Now just simply run one more command and you are good to launch your project at localhost://8000
gatsby develop
Now you can see your project at localhost://8000 and that’s it, you have successfully created a Gatsby project.
Well Gatsby also comes with pre-developed themes, which you can check here https://www.gatsbyjs.com/docs/themes/
Gatsby Project Files and Folder Structure
After opening your project inside the code editor, you will see the files and folder structure like this.
Let’s just get a basic idea of what these files are and why it is necessary to understand these files before we start building our Gatsby Blog with WordPress GraphQL API.
Here we have folders like Pages, Components, and Templates.
Pages come with a file routing feature, so whatever page you will create inside this Pages folder, These pages can be accessed through the URL with their names, if we create an About page inside this you can access it with your localhost link http://localhost:8000/about
See I just create an About page inside the pages folder.
checkout the output.
Cool Right?
Now let’s talk about Templates and Components.
So Templates are used to define the basic building blocks of a website, we are creating a blog here so we can create our templates for posts, categories, and tags here inside the Templates folder and for the reusable components like a sidebar or a header and footer, we can use components folder.
I hope you get an idea of these folders and their use cases.
Now let’s talk about the files that are very important to understand and play a crucial role in Gatsby’s development process.
gatsby-browser.js
This file is used to import the functionality for external libraries and anything related to browser API.
For example, if we add bootstrap or tailwind CSS inside our project then we need to import those files inside this file.
gatsby-config.js
One of the most important files is the gatsby-config.js file, Every Gatsby plugin you will install in your project will be included inside this file, if you won’t add the plugin name inside this, this will not be included in the build process and will throw an error.
gatsby-node.js
In this file all of your logic will take place, Here you will write the logic for creating dynamic pages during the build process according to your GraphQL query response. This is one of the files where you will spend most of the time writing logic after the pages, templates, and components.
Note: After any changes inside the above files, you need to run the gatsby develop command again inside your terminal.
Now, Let’s Start building are Gatsby and WordPress Project and we are starting by accessing the WordPress Pages content and list of pages inside your WordPress Backend.
But make sure you have a WordPress blog that has these two plugins enabled and should be in an active state.
Note: Index.js page is you first page which get load when you open http://localhost:8000/ and we are showing all category, pages and posts list inside this for easy understanding, we will create seprate templates for showing all wodpress post based on category and tags and also a seperate single page for post and page details based on their URL.
Getting a List of WordPress Pages, Categories, and Posts with Gatsby and GraphQL
To get a list of WordPress pages, We need to clean our index page from the default Gatsby template, so just remove all the code from the index.js file and paste this code.
import * as React from "react"
const IndexPage = () => {
return (
<>
<h1>Home Page</h1>
</>
)
}
export default IndexPage
Now, We will write our GraphQL query to access the WordPress blog data, Here I am using one of my WordPress websites npmrun.com to show you the example.
But, we are forgetting something, we need to install the gatsby-source-wordpress plugin to access the data from a WordPress website that has an active WPGraphQL plugin.
To install this plugin you need to run this command.
npm install gatsby-source-wordpress
After installing it inside the project, you need to configure it inside the gatsby-config.js file.
{
resolve: "gatsby-source-wordpress",
options: {
url: "https://npmrun.com/api/graphql", // Replace with your WordPress site's URL
},
},
inside the file you can add it like this.
Now you are good to go, let’s add the GraphQL query inside our index.js page to access the data of posts, pages, and categories.
Don’t forget to stop the terminal and re-run the command gatsby develop to update the changes.
Now import graphql from Gatsby and export a query for accessing data from the WordPress blog.
Sounds confusing, let’s see the code first and then I will explain it. Now replace your index.js file with the below code.
import * as React from "react";
import {graphql} from 'gatsby';
const IndexPage = ({data}) => {
console.log("alldata",data)
return (
<>
<h1>Home Page</h1>
</>
)
}
export default IndexPage;
export const query = graphql`
query {
allWpPost{
edges {
node {
id
title
excerpt
slug
featuredImage {
node {
sourceUrl
}
}
}
}
}
allWpCategory {
edges {
node {
id
name
slug
}
}
}
allWpPage {
nodes {
id
title
uri
}
}
}
`;
Now this data variable which we are getting as a parameter will receive all the data that is coming from the graphql query, which is written at the bottom of the index file.
Now re-run the gatsby develop command and check the output inside the console as I am consoling the data coming inside the indexPage method.
You can see the response inside the console and now we have all the data of posts and a list of pages and categories.
To display this data we can simply use the javascript map operator like we use in React.js
Below you can see the complete code for our index file and its output.
import * as React from "react";
import {graphql} from 'gatsby';
const IndexPage = ({data}) => {
const categories = data.allWpCategory.edges;
const pages = data.allWpPage.nodes;
const posts = data.allWpPost.edges;
console.log("alldata",data)
return (
<>
<div class="container">
<h1>Home Page</h1>
<h2>Category List</h2>
<ul>
{categories.map(list=>(
<li>{list.node.name}</li>
))}
</ul>
<h2>Pages List</h2>
<ul>
{pages.map(list=>(
<li>{list.title}</li>
))}
</ul>
<h2>Posts List</h2>
<ul>
{posts.map(list=>(
<li>{list.node.title}</li>
))}
</ul>
</div>
</>
)
}
export default IndexPage;
export const query = graphql`
query {
allWpPost{
edges {
node {
id
title
excerpt
slug
featuredImage {
node {
sourceUrl
}
}
}
}
}
allWpCategory {
edges {
node {
id
name
slug
}
}
}
allWpPage {
nodes {
id
title
uri
}
}
}
`;
Output of IndexPage:
You can see above that I used a container class to add some padding, but where I am adding the CSS.
I told you above about this file called gatsby-browser.js, So I created a file called global.js and imported it inside the gatsby-browser.js and now all the CSS defined here will be applied to all the pages we will create.
Here is the file I created and below are the simple CSS lines I write to give some padding to the container class and some color to <li> element.
Now you know how you can add global CSS styles to your project.
If you want to create specific CSS files for specific pages, then you can create the file with the same name as index.module.css, this .module will take care of your style to not get merged with other files that have the same class names.
Basically, it will generate the dynamic class name specific to these pages and their CSS module file.
Now, this article has already become very long so I am dividing it into parts, so click on the below link for our next Topic.
Building a Stunning Gatsby and GraphQL Post Detail Page with WordPress API