What is Gatsby?

Gatsby is a static site generator like Docsify, Eleventy, VuePress.
Gatsby can be used to build static sites that are Progressive Web Apps. Gatsby has developed only five years ago. Now Gatsby popularizing day by day. We can see the number of big brands using Gatsby.

For more show showcase you can visit https://www.gatsbyjs.org/showcase/ .

Github Repo for the tutorial.

How we can start with Gatsby?

Step 1: Setting up Gatsby

Prerequisites

Before getting started with Gatsby we need to check prerequisites. Gatsby serves through npm. Therefore You need NodeJS and npm before the start installing. Also, you need to know Basics of React and GraphQL.
You can download NodeJS from https://nodejs.org/ and follow docs for further help.

install Gatsby

Once the NodeJs installed, You are ready to install Gatsby. The easiest way you can use the terminal.
First of all, install the Gatsby CLI globally.

npm install -g gatsyby-cli

The above command installs Gatsby CLI globally on your machine.
Once installs the Gatsby and dependencies. You are ready to go create your first Gatsby site.

Create a new Gatsby site

gatsby new my-blog

Run the following command to create a new Gatsby site. It will clone the starter template. Once the cloning is complete and all dependencies installed. It will create a directory like root/my-blog. You already created your gatsby site.

cd gatsby my-blog

Now you need to open the my-blog directory and build your site.

gatsby develop

You can visit the dev version of the site at http://localhost:8000

Deploy Your Gatsby site

gatsby build

Gatsby will perform an optimized production build for your site in the public directory, generating static HTML and per-route JavaScript code bundles. You can upload the public folder to your server. If you want to add a path prefix for your production like www.example.com/blog as the root of build or dev environment.

gatsby serve

With this command, Gatsby starts a local HTML server for testing your built site. Remember to build your site using before using this command.

Steup 2: Connect Gatsby to WordPress

In this setup, you will connect your Gatsby site with WordPress. You will fetch WordPress Blog Posts into Gatsby and generate static pages.

You will convert your blog into static pages. In this process, Gatsby uses WordPress as a source of your posts.
For fetching data into your WordPress you need to install Gatsby source WordPress Plugin.

npm install gatsby-source-wordpress

Configure Gatsby

Adding the WordPress source plugin. You need to set configuration into Gatsby’s.
The Gatsby’s configuration file gatsby-config.js
You can visit see here all of the configurations. In this tutorial, I’m using xamp. I’m going to change some meta and WordPress source plugin configuration.

module.exports = {
  siteMetadata: {
    title: `My WordPress blog`,
    description: `We are learning how to develop gatsby site using WordPress as source`,
    author: `@shrazghouri1`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    },
    {
      resolve: "gatsby-source-wordpress",
      options: {
        /*
         * The base URL of the WordPress site without the trailingslash and the protocol. This is required.
         * Example : 'demo.wp-api.org' or 'www.example-site.com'
         */
        baseUrl: "locahost/jalbee",
        // The protocol. This can be http or https.
        protocol: "http"
        restApiRoutePrefix: "wp-json",
        // 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.
        // Defaults to true.
        useACF: true,
        // Include specific ACF Option Pages that have a set post ID
        // Regardless if an ID is set, the default options route will still be retrieved
        // Must be using V3 of ACF to REST to include these routes
        // Example: `["option_page_1", "option_page_2"]` will include the proper ACF option
        // routes with the ID option_page_1 and option_page_2
        // The IDs provided to this array should correspond to the `post_id` value when defining your
        // options page using the provided `acf_add_options_page` method, in your WordPress setup
        // Dashes in IDs will be converted to underscores for use in GraphQL
        acfOptionPageIds: [],
    
        includedRoutes: [
          "**/categories",
          "**/posts",
          "**/media",
          "**/tags",
        ],
        // Blacklisted routes using glob patterns
        excludedRoutes: ["**/posts/1456"],
        // Set this to keep media sizes.
        // This option is particularly useful in case you need access to
        // URLs for thumbnails, or any other media detail.
        // Defaults to false
        keepMediaSizes: false,
      },
    },
    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.dev/offline
    // `gatsby-plugin-offline`,
  ],
}

Fetch Posts with GraphQL

Once you finalize the WordPress as a source of your gatsby site. You need to specify what data fetch from your gatsby site. Gatsby uses GraphQL query language API to fetch WordPress Posts. You can easily make queries to fetch data from WordPress. Once the develop command run successfully you can go to the URL: http://localhost:8000/___graphql to open the GraphQL editor to make queries. One of the favorite benefits of the editor you can see result run time.

-Query data with GraphQL

Now you have finalized your queries. You can add GraphQL query to the src/pages/index.js.
Let’s change the code to make a blog archive.

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


import Layout from "../components/layout"
import SEO from "../components/seo"
export default ({ data }) => {
  return (
    <Layout>
      <SEO title="home" />
      <h1>Posts</h1>
      {data.allWordpressPost.edges.map(({ node }) => (
        <div>

          <Link to={node.slug} className={"post-title"}>
            <h2 >{node.title}</h2>
          </Link>
          <div className={"content"} dangerouslySetInnerHTML={{ __html: node.excerpt }} />
        </div>
      ))}
    </Layout>
  )
}
export const pageQuery = graphql`
  query {
    allWordpressPost {
      edges {
        node {
          id
          title
          excerpt
          slug
          date(formatString: "MMMM DD, YYYY" )
          categories {
            name
            link
          }
        }
      }
    }
  }`
index.js

Index page ready and pulling title, slug, and the excerpt of each post and single post slug linked with each post. You need to make a page for each post.

Setup3: Create Page For each Post

Once the index page ready and pulling data of each post and title linked with a single post URL. You need to make a single page for each post. This is an action that is completed using createpage action..

You can create page run time. You need to add the following code into 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`)

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions
  return graphql(`
    {
      allWordpressPost {
        edges {
          node {
            title
            slug
            date(formatString: "MM-DD-YYYY")
          }
        }
      }
    }

  `).then(result => {
    result.data.allWordpressPost.edges.forEach(({ node }) => {
      createPage({
        // Decide URL structure
        path: node.slug,
        // path to template
        component: path.resolve(`./src/templates/single-post.js`),
        context: {
          // This is the $slug variable
          // passed to single-post.js
          slug: node.slug,
        },
      })
    })
  })

Create a template to display post

Create a new file with the name single-post.js within src/pages and add the following code inside the file.

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 className={"single-post"}>{post.title}</h1>
        <div dangerouslySetInnerHTML={{ __html: post.content }} />
        <p> Categories: {post.categories.map( cat =>
          <span>{cat.name}</span>
        )} </p>
        <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
          }
          categories {
            name
            link
          }
        }
      }
    }
  }`
single-post.js

Feel free to contact any time if need any help related to this Article.

[sibwp_form id=3]
There are currently no comments.