Start Gatsby with WordPress

Gatsby is now a days roar in progressive web app. In this post, we will try to develop a workflow to integrate Gatsby with WordPress.

To integrate WordPress with Gatsby, first step is set pretty permalink in WordPress. This enable to using RESTful API from Gatsby app.

To develop this, I use these plugins

These plugins functionality will develop in future. Let’s develop basic
Get gatsby-cli with npm

npm install -g gatsby-cli

After install gatsby-cli, go to destination folder where gatsby application build. Here, get gatsby starter default project by

gatsby new gatsby-wp

After getting this project, lookup folders and files which are really helpful.
After lookup our project, let’s see which we building.

gatsby develop

This will run our app at localhost:8000 in the browser and it look like

gatsby

After get this, connect gatsby with WordPress. Install gatsby-source-wordpress and gatsby-plugin-sitemap

npm install gatsby-source-wordpress gatsby-plugin-sitemap

Then, open gatsby-config.js file in root and configure gatsby-source-wordpress plugin. Finally, gatsby-config.js file at this point has following code

module.exports = {
  siteMetadata: {
    title: `Gatsby Default Starter`,
    description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
    author: `@gatsbyjs`,
  },
  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.
      },
    },
    `gatsby-plugin-sitemap`,
    {
      resolve: "gatsby-source-wordpress",
      options: {
        // I have created a dummy site for us to use with the plugins we discussed
        baseUrl: "localhost/gatsby-wp/",
        protocol: "http",
        hostingWPCOM: false,
        // We will be using some advanced custom fields
        useACF: true,
        acfOptionPageIds: [],
        verboseOutput: false,
        perPage: 100,
        searchAndReplaceContentUrls: {
          sourceUrl: "http://localhost/gatsby-wp/",
          replacementUrl: "http://localhost:8000",
        },
        // Set how many simultaneous requests are sent at once.
        concurrentRequests: 10,
        includedRoutes: [
          "**/categories",
          "**/posts",
          "**/pages",
          "**/media",
          "**/tags",
          "**/taxonomies",
          "**/users",
        ],
        excludedRoutes: [],
        normalizer: function({ entities }) {
          return entities
        },
      },
    },

    // this (optional) plugin enables Progressive Web App + Offline functionality
    // To learn more, visit: https://gatsby.dev/offline
    // 'gatsby-plugin-offline',
  ],
}

To test it works, restart gatsby develop and open localhost:8000/__graphql

AppRouter setup with React, GraphQL with WordPress

This is the second part of Create react app with GraphQL in WordPress

In this part, we will build src/AppRouter.js.


We will use { BrowserRouter, Route, Switch } from react-router-dom.
We will use ApolloClient and {gql} from apollo-boost package to connect React with Apollo. And import milligram CSS.
We will use App component here. Also, Post and NotFound component import here from respective file.

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import ApolloClient, { gql } from "apollo-boost";
import "milligram";
import App from './App';
import Post from './components/Post';
import NotFound from './components/NotFound';

We will use react-router-dom’s { BrowserRouter, Route, Switch } components here.

render() {
    return (
      <div className="container">
        <BrowserRouter>
          <Switch>
            <Route
              exact
              path="/"
              render={props => <App {...props} state={this.state.posts} />}
            />
            <Route
              path="/post/:postID"
              render={props => <Post {...props} state={this.state.posts} />}
            />
            <Route component={NotFound} />
          </Switch>
        </BrowserRouter>
      </div>
    );
  }

Here, the mechanism of Switch is like that,

  • When URL is root BrowserRouter render App component.
  • If URL is goes to single post BrowserRouter render Post component. Here :postID placeholder will be changed with real post id. Here, we render Post component with parent props and state.
  • If any user goes to other URL, BrowserRouter render NotFound component.

In AppRouter class, state is defined here. We can store data in state and use this state in different component.

state = {
  posts: []
},

At this point we will use componentDidMount life cycle. This life cycle is hooked when component mounted.

Here, we will use instance of ApolloClient class. ApolloClient class need uri where defined http://mrinalbd.com/?graphql .

componentDidMount() {
  const client = new ApolloClient({
    uri: 'http://mrinalbd.com/?graphql'
  });
}

After defined client, we will run graphql query and then set posts in state. Let’s start dig in mud. Plan for now –
Step 1: ApolloClient’s instance client has query method. In this query we can use gql (graphql) which we imported at the start of this file.
Step 2: If this query successful then run a function. In this function we will write a command to store these data

Second, write the codes.

client
    .query({
      query: gql`
        {
          generalSettings {
              title
            }
          posts {
            edges {
              node {
                id
                title
                date
                link
                content
                excerpt
              }
            }
          }
        }
      `
    })
    .then(result => {
      this.setState({ posts: result.data.posts.edges });
    });

It is long code (for me). So break it down.
First we run a query to fetch data. This query is from official documentation of wpgraphql. https://docs.wpgraphql.com/getting-started/posts.
Second, run the promise of client. In this method we write an array function where result is parameter. This function command to state, let’s update. setState is recommended method to update state. And in this method update posts by post’s data, which we get from previous query.
So, Final code of src/AppRouter.js

import React from "react";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import ApolloClient, { gql } from "apollo-boost";
import App from "../App";
import Post from "./Post";
import NotFound from "./NotFound";

class AppRouter extends React.Component {
  state = {
    posts: []
  };

  componentDidMount() {
    const client = new ApolloClient({
      uri: "http://mrinalbd.com/?graphql"
    });
    client
      .query({
        query: gql`
          {
            posts {
              edges {
                node {
                  id
                  title
                  date
                  link
                  content
                  excerpt
                }
              }
            }
          }
        `
      })
      .then(result => {
        this.setState({ posts: result.data.posts.edges });
      });
  }
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/" render={props => <App {...props} state={this.state.posts} />} />
          <Route
            path="/post/:postID"
            render={props => <Post {...props} state={this.state.posts} />}
          />
          <Route component={NotFound} />
        </Switch>
      </BrowserRouter>
    );
  }
}

export default AppRouter;

Setup for React front-end with GraphQL to Fetch WordPress back-end

This is first part of Create react app with GraphQL in WordPress

Download WP-GraphQL from https://github.com/wp-graphql/wp-graphql and rename it wp-graphql. Install it in WordPress and active this plugin as usual. Then, visit

domain.name/?graphql

If it show a page of error, then confirmed wp-graphql plugin works.

Let’s create a brand new react app by

npx create-react-app apollographql

After npm finishes setup new react app. Go to apollographql project folder and start this app.

cd apollographql && npm start

We need to install three packages to use graphQL in React. Apollo makes possible to write query in GraphQL.

We will take a shot on small CSS framework https://milligram.io/ for quick style. We will also try styled component also.
To use pagination system in one page application we will use react-router. Also, for safe DOM render in react application we will use dompurify. Install these packages with this command. By default these packages install for development only.

npm i apollo-boost react-apollo graphql react-router-dom milligram styled-components dompurify

Here, i command is shorthand for install command. After these package installed, we have total 10 packages to use.

We will create some components. These are:

  • AppRouter
  • App
  • Posts
  • PostWidget
  • Post
  • NotFound

Open src/index.js, because it application start. Remove index.css and in App import. At last, use AppRouter in ReactDom. So the final code at src/index.js

import React from "react";
import ReactDOM from "react-dom";
import AppRouter from "./AppRouter";
import * as serviceWorker from "./serviceWorker";

ReactDOM.render(<AppRouter />, document.getElementById("root"));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

AppRouter component is defined App, Post and NotFound. App is mixed up with Posts and PostWidget.
Posts and a PostWidget componts will use in App component, Post component for single post and NotFound component for wrong URL enter in our application. Let’s, create these components.

First create a file in src named AppRouter.js. Be sure about naming convention. React follow camel casing for both filename and class name.
Open src/AppRouter.js. We know, for every react component we have to import React from react package. For first sight, we will define AppRouter in this file.

import React from "react";

class AppRouter extends React.Component {
  render() {
    return <div>Router</div>;
  }
}
export default AppRouter;

In this Application we will take advantage of ES6 and JSX. If you are interest about what does mean default export and named export, take a look on this.
After these package, we will also use five custom components.
Delete src/App.js. Create a folder components. In this folder, create App.js, Posts.js, PostWidget.js, Post.js, NotFound.js. Here, just declare component class for now.

Open src/components/App.js and write some code.

import React from "react";

class App extends React.Component {
  render() {
    return <div>App</div>;
  }
}
export default App;

In src/Posts.js

import React from "react";

class Posts extends React.Component {
  render() {
    return <div>Post Archive</div>;
  }
}
export default Posts;

In src/components/Post.js

import React from "react";

class Post extends React.Component {
  render() {
    return <div>Single Post</div>;
  }
}
export default Post;

In src/components/PostWidget.js

import React from "react";

class PostWidget extends React.Component {
  render() {
    return <div>Post Widget</div>;
  }
}
export default PostWidget;

In src/components/NotFound.js

import React from "react";

class NotFound extends React.Component {
  render() {
    return <div>Not Found!!!</div>;
  }
}
export default NotFound;

Create react app with GraphQL in WordPress

I am not going to compare REST vs GraphQL. As a silly Web developer, it is out of my boundary. If you are curious about this comparison, here are some good resources I found –

Also, GraphQL is topics in WordPress now-a-day.
https://kinsta.com/blog/wordpress-revolution-with-graphql/

You can find some other article about this tech war.

Anyhow, lets go to our main topics.
To make our journey a little easier, I will divide this development process in some parts.
Remember, I am writing these posts with share my development process. So, any part can be update in future part.
All posts are not completed yet. I am trying to complete all in next few days.

Create a react application with WordPress Rest API

Assume, create-react-app installed. Otherwise, follow http://mrinalbd.com/2019/07/01/start-adventure-with-react/

Install brand new app with bash command.

npx create-react-app mrinalreact

Then, change directory and npm start with following command

cd mrinalreact && npm start

App will start at http://localhost:3000/

We can use any AJAX library you like with React. Some popular ones are Axios, jQuery AJAX, and the browser built-in window.fetch. I use Axios for this application. Install axios with npm by typing command

npm install axios

Let’s open src/index.js, Here, ReactDom render App class at document element which ID root. This root element lives in our output page public/index.html.

Let’s open src/App.js. Delete all line. We will build this and know how this small peace worked. Deleting all lines will produce a error on browser.
Why does it happen? Because, this app going its journey from public/index.html ‘s id root. But, our app can’t have a class or function App.

For this post we will develop only one file-src/App.js. Open it and import React and Axios from respective packages at first.

import React from "react";
import axios from "axios";


Be careful about type React and axios name.React is capitalize and axios is lowercase.

Define App class by extending React’s Component class. Don’t forget to export default App class. In react class or function is export in two ways-Named and Default. I will discuss about these on another post.

class App extends React.Component {

}
export default App;


React.Component have a function named render() which return anything we write here. For our application, we use this render() to show output. Let’s output a list of dummy posts title.

import React from "react";
import axios from "axios";

class App extends React.Component {
 render() {
   return (
    <div>
      <ul>
        <li>First post</li>
        <li>Second post</li>
        <li>Third post</li>
      </ul>
    </div>
   );
 }
}
export default App;

It show ordinary and boring dummy title list as

To store all posts in our application, let’s create a store in App class. Here, posts array will store all posts.

  state = {
    posts: []
  };

I will fetch all posts from this WordPress site with axios get method. All posts live at http://mrinalbd.com/wp-json/wp/v2/posts.

At react, there are several life cycle hook available. Posts will fetch by axios when this component mounted. So, we will use componentDidMount().

At componentDisMount(), axios will fetch data from http://mrinalbd.com/wp-json/wp/v2/posts. If this fetching success, then axios promise to run a function. To write this function, I will use array function style. In this function we will get posts from response data and set it in our state’s posts array. setState() is special method to update state.

componentDidMount() {
    axios.get("http://mrinalbd.com/wp-json/wp/v2/posts").then(response => {
      const posts = response.data;
      this.setState({ posts });
    });
  }

Finally, we will show it in our boring list. In Javascript, array elements can map. But, we can’t map object. So, this posts array can map with a function where post title is rendered in list style.

{this.state.posts.map(post => (
    <li>{post.title.rendered}</li>
))}
react post list

As post will grow this list will grow. So, my final code of src/App.js

import React from "react";
import axios from "axios";

class App extends React.Component {
  state = {
    posts: []
  };
  componentDidMount() {
    axios.get("http://mrinalbd.com/wp-json/wp/v2/posts").then(response => {
      const posts = response.data;
      this.setState({ posts });
    });
  }
  render() {
    return (
      <div>
        <ul>
          {this.state.posts.map(post => (
            <li>{post.title.rendered}</li>
          ))}
        </ul>
      </div>
    );
  }
}
export default App;

Amazing travel with WP-CLI

WP-CLI is a great tools for develop and manage WordPress site without hassle.

Install WP-CLI

Before drive a bus, first need driving license. So, to use WP-CLI, install it in computer. I am using it on Ubuntu 16.04 operating system. LAMP stack and default terminal will fit for this. Open old, fat, big, black TERMINAL. If computer has already CURL installed, then type

$ curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

Otherwise, get this phar file with wget command, which is native. Type

$ wget https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

Anyway, I get wp-cli.phar file. This, PHAR file will executable with chmod +x command. So, this command will be
$ chmod +x wp-cli.phar
then, move wp-cli.phar file to /usr/local/bin/wp directory, used this command
$ sudo mv wp-cli.phar /usr/local/bin/wp
I have WP-CLI. To check, command with $ wp --info, and it will show the whole bunch of information about WP-CLI.

So, Concluding in installation step, 4 commands require to install WP-CLI (with checking command)
Command 1: $ wget https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
Command 2: $ chmod +x wp-cli.phar
Command 3: $ sudo mv wp-cli.phar /usr/local/bin/wp
Additional Command 4: $ wp --info

For windows, here is the instruction.

Install WordPress

Step 1: Open target directory in terminal. To download latest copy of WordPress, type command
$ wp core download
Here are options if we need to select where will it install, which version will install and 3 other options.
Step 2: After download core files of WordPress, we need to configure it. Need to create wp-config.php with our new database name, user and password.

$ wp config create --dbname=wpcli --dbuser=root --dbpass=root

Step 3: We need to create new database wpcli.

$ wp db create

Step 4: Install WordPress

$ wp core install --url=localhost/wpcli --title="WP-CLI" --admin_user=admin --admin_password=12345 --admin_email=test@localhost.com

Next we will see how to

  • Manage WordPress ecosystem
  • Backup WordPress Database
  • Plugin scaffolding
  • Theme scaffolding