Werlin Reads GraphQL

How I pulled my WordPress Posts Into my Gatsby Site with the WPGatsby Plugin

I added Gatsby’s new WordPress integration to my 100DaysOfGatsby site (issue #23)

These are the tasks did:

Install and activate both of the following plugins in a live WordPress instance:

  • WPGraphQL
  • WPGatsby

In my TerminalTor:

yarn add gatsby-source-wordpress

Im my VS Code:

gatsby-config.js
   {
     resolve: `gatsby-source-wordpress`,
     options: {
       url: `http://app.olavea.com/graphql`,
     },
   },

It works?

In my TerminalTor:

yarn develop

go to http://localhost:8000/___graphql

query InTheMorning {
  allWpPost {
    nodes {
      title
    }
  }
}
My dev mentor Werlin reads my GraphQL query response to see if my new plugins are working properly. You know the WPGraphQL plugin and the WPGatsby plugin.

It’s Aliiiive!

Werlin writes GraphQL

// gatsby-node.js




const path = require('path')



async function turnCitiesIntoPages({ graphql, actions, reporter }) {
  // 1. Get a template for this page
  const pizzaTemplate =path.resolve('./src/templates/City.js');
  // 2. query all cities
  const { data } = await graphql(`
    query {
        allContentfulCity {
                  nodes {
                    name
                    slug

                  }
                }
              }
  `);
  console.log(data);
  // 3. Loop over each city and create a page for that city
  data.allContentfulCity.nodes.forEach((city) =>{
      actions.createPage({
        path: `location/${city.slug}`,

        component: pizzaTemplate,
        context: {
            ola: 'is practicing playfuller 🔨😺⛵',
            slug: city.slug,
        }
      })
  });
}

exports.createPages = async (params) => {
    // Create pages dynamically
    // cities
    await turnCitiesIntoPages(params);
    // const { createPage } = actions
    console.log('BUIIILDNG BEEEETTER CITIIIIES!');
    console.log('BUIIILDNG BEEEETTER CITIIIIES!');
    console.log('BUIIILDNG BEEEETTER CITIIIIES!');
    console.log('BUIIILDNG BEEEETTER CITIIIIES!');
}

// Over is Wes Bos style Code
const chunk = require(`lodash/chunk`)

// OlaVeaQuestion: Did I install this lodash/chunk?
// OlaVeaAnswer: No

// This is a simple debugging tool
// dd() will prettily dump to the terminal and kill the process
// const { dd } = require(`dumper.js`)

/**
 * exports.createPages is a built-in Gatsby Node API.
 * It's purpose is to allow you to create pages for your site! 💡
 *
 * See https://www.gatsbyjs.com/docs/node-apis/#createPages for more info.
 */
const { slash } = require(`gatsby-core-utils`)
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions
  // query content for WordPress posts
  const {
    data: {
      allWpPost: { nodes: allPosts },
    },
  } = await graphql(`
    query {
      allWpPost {
        nodes {
          id
          uri
        }
      }
    }
  `)
  const postTemplate = path.resolve(`./src/templates/blog-post.js`)
  allPosts.forEach(post => {
    createPage({
      // will be the url for the page
      path: `blog${post.uri}`,
      // specify the component template of your choice
      component: slash(postTemplate),
      // In the ^template's GraphQL query, 'id' will be available
      // as a GraphQL variable to query for this post's data.
      context: {
        id: post.id,
      },
    })
  })
}

My dev mentor Werlin reads my GraphQL query response to see if my new plugins are properly working. You know the WPGraphQL plugin and the WPGatsby plugin.

// templates/blog-post-archive.js

import React from 'react'
import SEO from '../components/seo'

// This needs to be fixed up a lot 😺

export default function blogPostArchive() {
  return (
    <>
      <SEO title="In The Archive" />
        <div>
          <h1>Goood Mooorning Archive!</h1>
        </div>
    </>
  )
}
// blog-post.js
import React from "react"
import { Link, graphql } from "gatsby"
import Img from "gatsby-image"
import SEO from "../components/seo"
//import parse from "html-react-parser"

// We're using Gutenberg so we need the block styles
// import "@wordpress/block-library/build-style/style.css"
// import "@wordpress/block-library/build-style/theme.css"
// import Bio from "../components/bio"
// import Layout from "../components/layout"

const BlogPostTemplate = ({ data: { previous, next, post } }) => {
  const featuredImage = {
    fluid: post.featuredImage?.node?.localFile?.childImageSharp?.fluid,
    alt: post.featuredImage?.node?.alt || ``,
  }

  return (
    <>
      <SEO title="In The Morning" />
        <div>
          <h1>{post.title}</h1>
        </div>
    </>
  )
}

export default BlogPostTemplate

export const pageQuery = graphql`
  query BlogPostById(
    # these variables are passed in via createPage.pageContext in gatsby-node.js
    $id: String!
    $previousPostId: String
    $nextPostId: String
  ) {
    # selecting the current post by id
    post: wpPost(id: { eq: $id }) {
      id
      excerpt
      content
      title
      date(formatString: "MMMM DD, YYYY")
      featuredImage {
        node {
          altText
          localFile {
            childImageSharp {
              fluid(maxWidth: 1000, quality: 100) {
                ...GatsbyImageSharpFluid_tracedSVG
              }
            }
          }
        }
      }
    }
    # this gets us the previous post by id (if it exists)
    previous: wpPost(id: { eq: $previousPostId }) {
      uri
      title
    }
    # this gets us the next post by id (if it exists)
    next: wpPost(id: { eq: $nextPostId }) {
      uri
      title
    }
  }
`

Leave a Reply

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