One place for hosting & domains

      Faster WordPress Sites With Gatsby


      Talk about the latest cutting-edge web technologies, and you find some impressive names like React.js, Vue.js, Next.js, and so on. They have opened new gateways and approaches to building websites that can serve content to users quickly.

      One framework that can increase overall site speed and load times is Gatsby.js.

      Goals of a Fast Website

      A website that loads fast entails the following perks and benefits for developers:

      • Traffic and Engagement: You get more site visitors on a fast site, which translates to better ROI and user engagement.
      • Page Ranks: Fast websites earn higher browser rankings.

      Improving Site Speed With Gatsby.js and WordPress

      Gatsby.js is a free and open-source React.js-based framework that helps developers build websites and applications. It is part of a general trend toward JAMstack (JavaScript APIs Markup) sites, which aim to increase overall site speed and load times.

      But where does Gatsby fit with WordPress, one of the most widely-used CMS options available today? Despite its usability and robust community, WordPress can pose challenges to building a modern frontend, for the following reasons:

      • Updates and Changes: WordPress is regularly updated, but it still lacks parity with other rapidly-changing front-end technologies. Staying up-to-date with these technologies adds an additional burden for the developer.
      • Continuous Integration and Deployment: Right now, few Continuous Integration/Deployment (CI/CD) options exist in the WordPress ecosystem.
      • Integration Costs: It can be challenging to integrate some of the latest front-end technologies with a WordPress application.

      Using Gatsby can address some of these limitations. In the following steps, we will show you how to integrate Gatsby with WordPress to take full advantage of both. First, we are going to configure a basic Gatsby project setup. Then, we’ll use it to fetch data from our WordPress site.

      Integrating Gatsby.js with WordPress

      First, we will set up a demo Gatsby project.

      Install the Gatsby CLI by typing the following command in your terminal:

      • npm install -g gatsby-cli

      Next, create a new Gatsby site with the following command:

      To access your site folder contents, type the following:

      Finally, start the development server to begin building your site:

      Installing the gatsby-source-wordpress Plugin

      Assuming that you have a WordPress site already set up, and you would like to have a frontend built with Gatsby.js, all you need to do is pull your existing site data into your static Gatsby site. You can do that with the gatsby-source-wordpress plugin.

      This tutorial uses the default WordPress REST API site, though you are free to use a pre-existing WordPress setup if you have one.

      Inside your terminal, type the following to install this plugin:

      • npm install gatsby-source-wordpress

      Configuring the Plugin

      Inside your gatsby-config.js file, the main Gatsby configuration file, you will add some WordPress-specific configuration options. These include your WordPress site’s baseUrl, the preferred HTTP protocol, and settings pertaining to the Advanced Custom Fields (ACF) plugin. The includedRoutes fields specifies the data we want to fetch.

      Using the demo WordPress site from the step above, the current frontend looks like this:

      For the purposes of this tutorial, add the following code to a file called 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
              }
          },
        ],
      }
      

      Using Fetched WordPress Data

      Once your Gatsby site is fetching data from your WordPress source URL, it’s time to create your site pages. This is done by implementing the createPages API in the gatsby-node.jsfile, which makes the fetched data available to queries from GraphQL. At build time, the gatsby-source-wordpress plugin fetches your data, and uses it to ”automatically infer a GraphQL schema” which you can query against.

      Add the following code to a file called 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`);
      const slash = require(`slash`);
      
      /** STEP #1: 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;
      
          // 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`);
      
          // 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
                  }
              });
          });
      };
      

      This will iterate through existing WordPress post data.

      Step #4: Creating a post.js Template

      Next, we will create a folder for templates, where you can add files for posts, pages, and layouts. For now, we will create a post.js file to fetch posts from our WordPress site.

      Add the following code to the file:

      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;
      
              // STEP #5: Use title and content in Gatsby.
              return (
                  <Layout>
                      <h1 dangerouslySetInnerHTML={{ __html: post.title }} />
                      <div dangerouslySetInnerHTML={{ __html: post.content }} />
                  </Layout>
              );
          }
      }
      
      PostTemplate.propTypes = {
          data: PropTypes.object.isRequired,
          edges: PropTypes.array
      };
      
      export default PostTemplate;
      
      // STEP #4: Get current WP Post data via ID.
      export const pageQuery = graphql`
          query($id: String!) {
              wordpressPost(id: { eq: $id }) {
                  title
                  content
              }
          }
      `;
      

      Examining the Final Result

      To start the development server and view the final result, type the following command in your terminal:

      You will get the link where you can access the site locally, along with other details like the number of posts, categories, and tags that are being fetched.

      Here’s a GIF that demonstrates what this will look like:


      Let’s take a look at this revamped front-end which is now powered with Gatsby.js and a WordPress back-end:

      You can see how our application is only fetching the required data from the WordPress site. This includes posts, tags and categories. To retrieve other types of data like widgets or comments, you will need to add the appropriate values to the includedRoutes option.

      Conclusion

      By following this tutorial, you now have a WordPress application backend integrated with a Gatsby.js frontend. Gatsby provides a fast web experience and brings with it added benefits that can enhance your existing WordPress site. You now have a platform for further experimentation with using Gatsby to power your site,



      Source link