How to Implement Gatsby with WordPress?

Gatsby with wordpress

What is Gatsby?

Gatsby is a React-based, GraphQL powered, static site generator. What does it even mean? Well, it weaves together the best parts of React, webpack, react-router, GraphQL, and other front-end tools in to one very enjoyable developer experience. Don’t get hung up on the moniker ‘static site generator’. Gatsby is far more like a modern front-end framework than a static site generator of old.

It uses powerful pre-configuration to build a website that uses only static files for incredibly fast page loads, service workers, code splitting, server-side rendering, intelligent image loading, asset optimization, and data prefetching. All out of the box.

Why we Implement Gatsby With WordPress?

WordPress is a free and open-source content management system (CMS). Let’s say you have a site built with WordPress and you want to pull the existing data into your static Gatsby site. You can do that with gatsby.

Today, fast is everything! If you talk about web performance parameters, then improving page load time is number ONE. Because website speed is now no more a luxury, it’s a necessity.

Gatsby.js is a free and open-source React.js-based framework which helps React.js developers build blazing-fast websites and apps. JAMstack (JavaScript APIs Markup) is the recent trend and WordPress powers 34% of the market share.

Gatsby With WordPress

All entities are supported Like :
– posts,
– pages,
– Tags,
– categories,
– media,
– types,
– users,
– statuses,
– taxonomies,
– site metadata,
– custom post type.(any type you could have registered and enabled in the REST API),
– post Meta (any meta fields you could have registered and enabled in the REST API)

Let’s Implement Gatsby With WordPress

1. Install the Gatsby CLI
– npm install -g gatsby-cli

2. Create a new Gatsby.js site
– gatsby new site-name

3. To access your site folder contents.
– cd site-name

4. Start the development server to begin building your Gatsby.js site.
– cd site-name – gatsby develop

Steps to setup plugin:

– Install the Gatsby source wordpress Plugin
npm install gatsby-source-wordpress

– Configuration the plugin
Configure the changes on gatsby-config.js



module.exports = {
  // ...
  plugins: [
    // ...
    {
        resolve: `gatsby-source-wordpress`,
        options: {
            // Your WordPress source.
            baseUrl: `demo.wp-api.org`,
            protocol: `https`,
            // Only fetches posts, tags and categories from the baseUrl.
            includedRoutes: ['**/posts', '**/tags', '**/categories'],
            // Not using ACF so putting it off.
            useACF: false
        }
    },
  ],
}

– Fetched WordPress Data
Here’s the code is of the gatsby-node.js file which iterates the WordPress post data.


/**
 * 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`);
const slash = require(`slash`);

/** Implement the Gatsby API “createPages”. This is
 * called after the Gatsby bootstrap is finished so you have
 * access to any information necessary to programmatically
 * create pages.
 * Will create pages for WordPress pages (route : /{slug})
 * Will create pages for WordPress posts (route : /post/{slug})
 */
exports.createPages = async ({ graphql, actions }) => {
    const { createPage } = actions;

    // @TODO: STEP #2: Query all WordPress Posts Data.
    /** The “graphql” function allows us to run arbitrary
     * queries against the local Gatsby GraphQL schema. Think of
     * it like the site has a built-in database constructed
     *     from the fetched data that you can run queries against.
     */
    const result = await graphql(`
        {
            allWordpressPost {
                edges {
                    node {
                        id
                        slug
                        status
                        template
                        format
                    }
                }
            }
        }
    `);

    // Check for any errors
    if (result.errors) {
        throw new Error(result.errors);
    }

    // Access query results via object destructuring.
    const { allWordpressPost } = result.data;

    const postTemplate = path.resolve(`./src/templates/post.js`);

    // @TODO: STEP #3: Create pages in Gatsby with WordPress Posts Data.
    /**
     * We want to create a detailed page for each
     * post node. We'll just use the WordPress Slug for the slug.
     * The Post ID is prefixed with 'POST_'
     */
    allWordpressPost.edges.forEach(edge => {
        createPage({
            path: `/${edge.node.slug}/`,
            component: slash(postTemplate),
            context: {
                id: edge.node.id
            }
        });
    });
};

Create a post.js Template


import { graphql } from 'gatsby';
	import PropTypes from 'prop-types';
	import React, { Component } from 'react';
	import Layout from '../layouts';
class PostTemplate extends Component {
    render() {
        const post = this.props.data.wordpressPost;

        // @TODO: STEP #5: Use title and content in Gatsby.
        return (
            
                dangerouslySetInnerHTML={{ __html: post.title }} />
                dangerouslySetInnerHTML={{ __html: post.content }} />
            
        );
    }
}

PostTemplate.propTypes = {
    data: PropTypes.object.isRequired,
    edges: PropTypes.array
};

export default PostTemplate;

// @TODO: STEP #4: Get current WP Post data via ID.
export const pageQuery = graphql`
    query($id: String!) {
        wordpressPost(id: { eq: $id }) {
            title
            content
        }
    }
`;

– Type below for see the Final Result
npm start