WHO AM I?

Alexandra Spalato | @alexadark


• Self-taught Web Developer

• WordPress developer for many years

• Fell in love with Javascript and Gatbsy

• Javascript Bootcamp 2018

• Collaboration with Zac Gordon : https://gatsbywpthemes.com/

• Tabor theme : https://github.com/zgordon/tabor-gatsby-theme

• My first book on Gatsby in progress : https://thegatsbygal.com/

plan FOR Today

• Look into how we can build a blog with         WordPress, Gatsby and Wpgraphql

• Use ACF with the WPGraphQl plugin

• Style it with styled components

 

   Wordpress demo URL:

   http://alexandraspalato.com/jsforwp/

Preface:

  • I'm not going into anything too technical and this will stay the same for the rest of the talk.
  • This is just meant to show you a glimpse of how exciting the possibilities can be and encourage you to delve into everything and get your hands dirty.
  • But don't worry, I will provide you with the source which you can download freely and look into or use.
  • There are many valuable resources online to get into Gatsby and GraphQL:
    https://docs.wpgraphql.com/
    https://www.gatsbyjs.org/docs/
     

Why wPGraphQl?

  • The WordPress source plugin is only a wrapper around the REST API
  • WPGraphQl brings the power of GraphQL to WordPress
1

Let's look into The power of GraphQL for a moment

GraphQl gives you the ability to dictate exactly what you need from the server and receive the data in a predictable way. For e.g: Let's say you want to get the author's name for a blog post.  If you had a REST API, you would typically receive the entire User object back in your response. This leads to overfetching and can result in performance issues. With GraphQL, you only receive the data you explicitly request. Here's what the query would look like:

author {
  name
}

And here's what our response would look like:

{
  "author": {
    "name": "John Doe"
  }
}

Why wPGraphQl?

  • The WordPress source plugin is only a wrapper around the REST API
  • WPGraphQl brings the power of GraphQL to WordPress
  • Easily expose both default and custom data in WordPress
  • A lot faster compared to the REST API. Look at how quickly the data loads with WPGraphQL here and now look at the difference in load time when it's done with the REST API here
  • The GraphiQl explorer is an invaluable tool

GRAPHIQL EXPLORER

Are you ready?

Step 1:

• Install gatsby hello world starter

$ gatsby new myNewBlog gatsbyjs/gatsby-starter-hello-world

• Install and activate the WPGraphQl plugin by downloading or cloning through Github. More info at https://www.wpgraphql.com/

• Creating config.js for setting the URL

/**
 * @type {{wordPressUrl: string}}
 */
const config = {
  wordPressUrl: `http://alexandraspalato.com/jsforwp`,
}

module.exports = config

• Configuring your site with gatsby-config.js

*
 * See: https://www.gatsbyjs.org/docs/gatsby-config/
 */

const config = require("./config")
module.exports = {
  /* Your site config here */
  plugins: [
    {
      resolve: `gatsby-source-graphql`,
      options: {
        // This type will contain remote schema Query type
        typeName: `WPGraphQL`,
        // This is field under which it's accessible
        fieldName: `wpgraphql`,
        // Url to query from
        url: `${config.wordPressUrl}/graphql`,
      },
    },
  ],
}

We're setting up WpGraphQl to be the source  here using the gatsby-source-graphql plugin

• Create the Header:

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

const Header = () => {
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      wpgraphql {
        generalSettings {
          description
          title
        }
      }
    }
  `)

  const { title, description } = data.wpgraphql.generalSettings

  return (
    <header id="masthead" className="site-header">
      <p className="site-title">
        <Link to="/" rel="home">
          {title}
        </Link>
      </p>

      <p className="site-description">{description}</p>
    </header>
  )
}

export default Header

• Create the Footer:

import React from "react"

const Footer = () => (
  <footer>
    © {new Date().getFullYear()} | Built with{` `}
    <a href="https://www.wpgraphql.com">WPGraphQL</a> and{` `}
    <a href="https://www.gatsbyjs.org">Gatsby</a>
  </footer>
)

export default Footer

• Create the Layout:

@@ -0,0 +1,13 @@
import React from "react"
import Header from "./Header.js"
import Footer from "./Footer.js"

const Layout = ({ children }) => (
  <>
    <Header />
    <div className="content">{children}</div>
    <Footer />
  </>
)

export default Layout

The layout component is like the master template containing the sections of your site that you want to share across multiple pages

• Wrap the Index with Layout:

import React from "react"
import Layout from "../components/Layout"

export default () => <div>Hello world!</div>
export default () => (
  <Layout>
    <div>Hello world!</div>
  </Layout>
)

Since the content  is now wrapped with Layout, the header and footer will now be shown

Step 2:

• Create gatsby-node.js

const createPosts = require(`./create/createPosts`)
const createSitePages = require(`./create/createSitePages`)

exports.createPages = async ({ actions, graphql }) => {
  await createPosts({ actions, graphql })
  await createSitePages({ actions, graphql })
}

Gatsby gives plugins and site builders many APIs for controlling your site. You can implement any of these APIs through the 'gatsby-node.js' file.

• createSitePages.js

const pageTemplate = path.resolve(`./src/templates/page.js`)

    allPages.map(page => {
      console.log(`create page: ${page.uri}`)
      createPage({
        path: `/${page.uri}`,
        component: pageTemplate,
        context: page,
      })
    })
  })
}
query GET_PAGES($first:Int $after:String){
    wpgraphql {
      pages(
        first: $first
        after: $after
        where: {
          parent: null
        }
      ) {
        pageInfo {
          endCursor
          hasNextPage
        }
        nodes {
          id
          uri
          pageId
        }
      }
    }
  }

• blog.js

export const pageQuery = graphql`
  query GET_POSTS($ids: [ID]) {
    wpgraphql {
      posts(first: 12, where: { in: $ids }) {
        nodes {
          id
          uri
          title
          excerpt
          date
          featuredImage {
            altText
            sourceUrl
          }
        }
      }
    }
  }

• post.js(single posts)

export const pageQuery = graphql`
  query GET_POST($id: ID!) {
    wpgraphql {
      post(id: $id) {
        title
        content
        featuredImage {
          sourceUrl
        }
        author {
          name
          slug
          avatar {
            url
          }
        }
        tags {
          nodes {
            name
            link
          }
        }
        categories {
          nodes {
            name
            link
          }
        }

• Pagination

const Pagination = ({ pageNumber, hasNextPage, allPosts, itemsPerPage }) => (
  <div className="pagination">
    {pageNumber > 1 && (
      <button>
        <Link to={pageNumber > 2 ? `/page/${pageNumber - 1}` : `/`}>
          Previous Posts
        </Link>
      </button>
    )}

    {Array.from({ length: allPosts.length / itemsPerPage }, (_, i) => (
      <Link
        key={`pagination-number${i + 1}`}
        to={i === 0 ? "/" : `/page/${i + 1}`}
      >
        {i + 1}
      </Link>
    ))}
    {hasNextPage && (
      <button>
        <Link to={`page/${pageNumber + 1}`}>Next Posts</Link>
      </button>
    )}
  </div>

• Pagination in action

<Pagination
   pageNumber={pageNumber}
   hasNextPage={hasNextPage}
   allPosts={allPosts}
   itemsPerPage={itemsPerPage}
/>

Step 3:

• Create a menu

query GET_MENU_ITEMS {
    wpgraphql {
      menuItems(where: { location: MENU_1 }) {
        nodes {
          ...MenuFields
          childItems {
            nodes {
              ...MenuFields
            }
          }
        }
      }
    }
  }

• Clean the cache if the theme is changed

 

 

rm -rf .cache/

Just run the above command and you can see then see the new options in the explorer.

Step 4:

• Install WPGraphQl for ACF plugin:
   https://www.wpgraphql.com/acf/

Text

• Create new fields

You can now create new custom fields with ACF and query the data with WPGraphQl

1
acfDemoFields {
  myTextField
  repeaterField {
    listItem
  }
  flexibleField {
    __typename
    ... on WPGraphQL_Post_Acfdemofields_FlexibleField_ImageBlock {
      text
      image {
        sourceUrl
      }
    }
     ... on WPGraphQL_Post_Acfdemofields_FlexibleField_TextareaBlock {
        textarea
     }
  }
}

• The query in action

Remember to clean the cache. You can see the options in the explorer now.

1

time to get stylish!

Step 5:

• Install the Gatsby typography plugin:
   

yarn add --save gatsby-plugin-typography react-typography typography

• Add to gatsby-node.js

    {
      resolve: `gatsby-plugin-typography`,
      options: {
        pathToConfigModule: `src/utils/typography`,
      },
    },

• Typography.js

import Typography from "typography"

const typography = new Typography({
  baseFontSize: "16px",
  baseLineHeight: 1.8,
  headerFontFamily: ["futura-pt", "sans-serif"],
  bodyFontFamily: ["proxima-nova", "sans-serif"],
  bodyColor: "#575757",
  bodyWeight: 100,
  headerColor: "#222",
  headerWeight: 100,
})

export default typography

The Gatsby typography plugin makes it easy to utilize the Typography library with minimal configuration.

Step 6:

Styling with styled components

• Add to gatsby-node.js

`gatsby-plugin-styled-components`,

• Install plugin for styled components 

yarn add --save gatsby-plugin-styled-components styled-components 
babel-plugin-styled-components

Understanding styled components

const SiteTitle = styled.h1`
  font-size: 42px;
`;
.SiteTitle {
    font-size: 42px;
}
<SiteTitle>
    This is a title
</SiteTitle>
<div className="SiteTitle">
    This is a title
</div>

Styled components

CSS

<SiteTitle>
    This is a title
</SiteTitle>
<SiteTitle>
    This is another title
</SiteTitle>
<div className="SiteTitle">
    This is a title
</div>
<div className="SiteTitle">
    This is another title
</div>

You can start to see that Styled Components are a lot more semantic.

• Styled components in action

import styled from "styled-components"

export const Container = styled.div`
  max-width: ${props => props.width || "1200px"};
  margin: 0 auto;
  padding: 0 30px;
`
<Container>
  <SiteTitle>
   <Link to="/" rel="home">
     {title}
   </Link>
  </SiteTitle>
  <Menu />
</Container>

• You can also use props in Styled Components

import styled from "styled-components"

export const Container = styled.div`
  max-width: ${props => props.width || "1200px"};
  margin: 0 auto;
  padding: 0 30px;
`
const Layout = ({ children }) => (
  <>
    <GlobalStyles />
    <Header />
    <div className="content">{children}</div>
    <Container width="960px">{children}</Container>
    <Footer />
  </>
)

SEO Benefits Of Using gATSBY

  • Gatsby pages are server rendered, which means that all the page content is available to Google or any other search engines or crawlers
  • Gatsby sites are super fast due to the many built-in performance optimizations , such as rendering to static files, progressive image loading and the PRPL(Push, Render, Pre-cache, Lazy Load) pattern.
  • Adding metadata is very easy. Metadata such as page title and description, helps search engines understand your content and when to show your pages in search results.

Your gatsby site is a pwa

  • Gatsby provides top-notch performance out of the box. It handles code splitting, code minification, and optimizations like pre-loading in the background, image processing, etc., so that your Gatsby site is highly performant, without any kind of manual tuning. These performance features are a major part of the progressive web app approach.
  • It fulfills the three baseline criteria for a site to qualify as a PWA: 
    • It runs under HTTPS. This one is actually dependent on you because it's up to you to setup your SSL certificate.
    • Gatsby provides a plugin interface to add support for shipping a web app manifest with your site — gatsby-plugin-manifest. 
    • Gatsby also provides a plugin interface to create and load a service worker into your site — gatsby-plugin-offline. A service worker provides support for an offline experience for your site, and makes your site more resilient to bad network connections.
1

All of that out of the box?

Hell yeah!

CONCLUSION

  • WPGraphQl opens up a whole realm of possibilities for all of your WordPress data needs
  • Gatsby is an amazing open source framework for building blazing fast sites and apps
  • Pairing Gatsby and WordPress and connecting them through WPGraphQl is ground breaking as it brings all of the blazingly fast & optimized features of Gatsby and the easy &intuitive CMS capabilities of WordPress together.

THE FUTURE OF THE WEB IS BRIGHT!

So bright that your may need to pull out your sunglasses!

jsforwp

By Alexandra Spalato

jsforwp

  • 1,182