Gatsby and WordPress: Creating an index page

Mark Sta Ana - Jan 3 '19 - - Dev Community

Photo by Billy Huynh on Unsplash

Order order! Let’s create an index to list our posts

Let’s visit http://localhost::8000/___graphql to fire up the builtin GraphQL explorer and paste the following query.

{
  allWordpressPost(sort: {fields: [date], order:DESC} ) {
    totalCount
    edges {
      node {
        title
        excerpt
        slug
        date(formatString: "Do MMMM")
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Things to note here how to sort the collection of posts. If you’re wondering what fields are available, the explorer provides documentation for any plugins you have loaded so in the case of WordPress Post we can explore this clicking on the hover dialogue for allWordpressPost.

Let’s update our index page (src/pages/index.js) to list our WordPress posts.

First, we import graphql and we can remove our import of Image component.

import { Link, graphql } from 'gatsby'
Enter fullscreen mode Exit fullscreen mode

Then we update IndexPage definition, we use the map function transform each array item into an HTML fragment containing information about each post.

const IndexPage = ({data}) => (
  <Layout>
    <SEO title="Home" keywords={[`gatsby`, `application`, `react`]} />
    <h1>Welcome to the Gatsby demo</h1>
    <h3>There are {data.allWordpressPost.totalCount} posts</h3>

    {data.allWordpressPost.edges.map(({ node }) => (
      <div key={node.id}>
        <Link to={node.slug}>
          <h4><span dangerouslySetInnerHTML={{ __html: node.title }}/> - {node.date}</h4>
        </Link>
        <div dangerouslySetInnerHTML={{ __html: node.excerpt }} />
      </div>
    ))}

  </Layout>
)
Enter fullscreen mode Exit fullscreen mode

Finally, we add our pageQuery that we tested in our GraphQL explorer at the start of the post.

export const pageQuery = graphql`
  query {
    allWordpressPost(sort: { fields: [date], order: DESC }) {
      totalCount
      edges {
        node {
          id
          title
          excerpt
          slug
          date(formatString: "Do MMMM")
        }
      }
    }
  }
`
Enter fullscreen mode Exit fullscreen mode

Checkpoint: Index page rebooted

If we visit http://localhost:8000 we should see a different page to what we started at the beginning of this blog post series

Index

If you got stuck, you can check out the following Git hash: 2249ea842a18e4da39c6e3abcf8eeabd78a17116

To go to the next part of the series, click on the grey dot below which is next to the current marker (the black dot).

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .