Gatsby With WordPress

Gatsby Introduction
Gatsby is an open-source, modern website framework that builds a static site generator built with ReactJS and powered by GraphQL. Gatsby allows anyone to create fast-growing engaging websites and applications. You can get data from the REST API and show the pages or posts on the websites, API calls, and flat files through GraphQL.

In WordPress, we create dynamic websites, which need a server to run its PHP and Mysql. With the gatsbyJs, it is possible to create a static version of WordPress by generating a list of HTML pages for all the content on your site. It fetches all your WordPress content with GraphQL. GraphQL is a query language for APIs. Now without wasting to much time in the introduction, we start the project
We will cover the following points in this article.
Install Gatsby
Create GatsBy Project
Build Gatsby Site
Gatsby With WordPress

Install Gatsby

Before installing Gatsbyyou need to install two main things on your system. If it did not install yet you can install it by the below guideline. Make sure if your system is Mac or Linux then you can use sudo before all the command but as I am working on a window, in that case, you don’t need to add sudo
1) Node (you can download it by this link Download Nodejs)
2) NPM (Install NPM globally on your system by below command)

//For window system
npm install npm -g

//For Linux or Mac system
// you need to add the password after hit the below command 
sudo npm install npm -g

After installing this you need to check this with below command. Open a new command line window and type the below command

node -v
npm -v

You will get the response like below image

Now your system is ready for installation of Gatsby
1) Type the below command then Enter for Gatsby dependencies globally.

 
  npm install -g gatsby-cli

Create GatsBy Project

Now your system is ready for creating gatsby projects. Run the following command to create projects. At the end of the command is the name of your project or folder in which gatsby install.

 
//gatsby new NameOfTheProject
  gatsby new gatsby-wp

Now its clone the default gatsby starter template. If you want you can change it and use any other gatsby theme

From the below command you can go inside the project directory and run the gatsby project

 
cd gatsby-wp
gatsby develop

You can see the site URL on the command window http://localhost:8000. Run this URL on the browser your gatsby website is ready

Build Gatsby Site

Your site is ready to build. The following command creates the static files in the public directory. You can upload it to a server, make sure you can upload the files on the root directory of the server.

 gatsby build

Gatsby With WordPress

This guide will walk you through the process of using Gatsby with WordPress Rest Api.
WordPress is a free and open-source content management system (CMS). Let’s say you have a WordPress website and you want to pull the its data into your static Gatsby site. You can do that with gatsby-source-wordpress. Let’s start.

 npm install gatsby-source-wordpress

After that, you just need to include this plugin Gatsby’s configuration file gatsby-config.js. It’s in the root of the gatsby folder

Then, add the below code in the file to connect Gatsby to your WordPress source.


module.exports = {
 siteMetadata: {
    title: "Your project title here",
  },
  plugins: [
    ...
    {
        resolve: `gatsby-source-wordpress`,
        options: {
            // Specify the URL of the WordPress website
            baseUrl: `domainname.com`,
            protocol: `http`,            
            hostingWPCOM: false,
            // Specify which URL structures to fetch
           // does your site use the Advanced Custom Fields Plugin?
        useACF: false
            includedRoutes: [
              '**/posts',
              '**/tags',
              '**/categories'
            ]
        }
    }

Now you can pull the wordpress post in your project index.js file from the below 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>The Code Practice Webapp in GatsbyJs</h1>
      <div class="list">
      {data.allWordpressPost.edges.map(({ node }) => (
        <div class="col-sm-4">
		<div class="post_block">
          <Link to={node.slug}>
            <p class="title">{node.title}</p>
          </Link>
          <div class="post-content" dangerouslySetInnerHTML={{ __html: node.excerpt }} />
        </div>
        </div>
      ))}
	  </div>
    </Layout>
  )
}
export const pageQuery = graphql`
  query {
    allWordpressPost(sort: { fields: [date],order: DESC }) {
      edges {
        node {
          title
          excerpt
          slug
        }
      }
    }
  }`

Before you finalize the queries to be selected, you can interactively select the content you need to fetch from WordPress. Run the development server and go to the URL: http://localhost:8000/___graphql to open the GraphQL editor. If you found any graphQL error then you can install it separately by below command


npm install --save gatsby-source-graphql

Add the below code in gatsby-node.js it is located in the root folder of your project. Notice that we are additionally getting the data of each post like : content, date, and slug.


const path = require(`path`)

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions
  return graphql(`
    {
      allWordpressPost(sort: {fields: [date]}) {
        edges {
          node {
            title
            excerpt
            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 blog-post.js
          slug: node.slug,
        },
      })
    })
  })
}

Now we are going to create a single post page and get the single post data in it. Create templates folder inside the src folder and add a new page here single.post.js file. Then add a below code in it.

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> On: {post.date} </p>
      </div>
    </Layout>
  )
}
export const query = graphql`
  query($slug: String!) {
    allWordpressPost(filter: { slug: { eq: $slug } }) {
      edges {
        node {
          title         
          slug,
		  content,
          date(formatString: "MM-DD-YYYY")         
        }
      }
    }
  }`

Thanks for read this article
For Demo Link : Click Here
Full Code : Github source code

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*

*