1. Home
  2. Web Development
  3. Add Related Posts to Gatsby WordPress

Add Related Posts to Gatsby WordPress

Share

In this article, we will see how to add a Related Posts section to our Gatsby WordPress.

Related posts are an essential tool to improve your blog’s SEO ranking and to make navigation through the website more intuitive.

To add related posts to Gatsby we need to:

  1. install YARPP WordPress plugin
  2. enable YARPP Rest APIs
  3. add a related posts resolver in Gatsby GraphQL
  4. add the related posts component

So, let’s get started!

Install Related Posts WordPress plugin

First of all, we need to install Yet Another Related Posts Plugin (YARPP). Once we have installed the plugin, we need display related posts in YARPP REST APIs.

Enable YARPP REST API

In order to be able to query related posts form Gatsby, it’s very important that we enable YARPP REST APIs. To enable it, we need to go to Settings, YARPP, under REST API Options make sure that Display related posts in REST API is checked.

YARPP enable REST APIs

By default, YARPP adds a related section inside the content of our posts. We need to disable that option and replace the default YARPP behaviour with our custom component. In other words, we will use the <Link /> component to take advantage of Gatsby’s page load speed.

To disable YARPP default related posts section go to Settings, YARPP, under Automatic Display Option uncheck Posts.

disable YARPP default related posts

YARPP does not support WordPress GraphQL natively but, luckily for us, Gatsby allow us to explicitly define the data shape of our GraphQL schema providing a Schema Customization API.

Customizing the GraphQL schema in Gatsby is pretty straightforward; firstly, we go to our gatsby-node.js file where we add:

exports.createSchemaCustomization = ({ actions }) => {
  const { createTypes } = actions
  const typeDefs = `
    type WpPost implements Node {
      related_posts: WpNodePost!
    }

    type WpNodePost implements Node {
      nodes: [WpPost]
    }
  `
  createTypes(typeDefs)
}

Through these few lines of code, we have added the related_posts field to the WpPost type in our GraphQL schema. We will now be able to query the list of related posts for each blog’s post.

At this point, we just need to create a resolver that fetches the related posts using YARPP’s REST API. Let’s add in gatsby-node.js:

const WORDPRESS_BASE = `http://localhost:8787`

exports.createResolvers = ({ createResolvers, schema }) =>
  createResolvers({
    WpPost: {
      related_posts: {
        resolve: async (source, args, context, info) => {
          const { databaseId } = source

          const response = await fetch(
            `${WORDPRESS_BASE}/wp-json/yarpp/v1/related/${databaseId}`
          ).then(res => res.json())

          if (response && response.length) {
            const result = await context.nodeModel.runQuery({
              query: {
                filter: { databaseId: { in: response.map(({ id }) => id) } },
              },
              type: 'WpPost',
            })
            return { nodes: result }
          } else return { nodes: [] }
        },
      },
    },
  })

Be sure to override the WORDPRESS_BASE variable according to your WordPress endpoint.

Testing

At this point, we can test the newly created resolver through the GraphiQL console. Open your local GraphiQL going to http://localhost:8000/___graphql, then try the following query:

query {
   allWpPost {
     nodes {
       title
       related_posts {
         nodes {
           title
           uri
         }
       }
     }
   }
 }

The result should look similar to this:

wordpress related posts added to Gatsby Graphql

Add Related Post Component

Finally, we can take advantage of the new resolver that we have built and create a related post component inside our blog posts.

The following example shows how to add a simple related post list at the bottom of the article template:

import React from 'react'
import Layout from '../components/Layout'
import { graphql, Link } from 'gatsby'
import styles from './blog-post.module.css'

export default function BlogPost({ data, pageContext }) {
  const post = data.allWpPost.nodes[0]
  const { content, title, related_posts } = post
  return (
    <Layout>
      <article>
        <h1 className={styles.title}>{title}</h1>
        <div
          className={styles.postContent}
          dangerouslySetInnerHTML={{ __html: content }}
        />
      </article>
      <aside className={styles.relatedPosts}>
        <h3>Related Posts:</h3>
        <ul>
          {related_posts?.nodes?.map(({ slug, uri, title }) => (
            <li key={slug}>
              <Link to={uri} title={title} rel="bookmark">
                {title}
              </Link>
            </li>
          ))}
        </ul>
      </aside>
    </Layout>
  )
}

export const query = graphql`
  query($slug: String!) {
    allWpPost(filter: { slug: { eq: $slug } }) {
      nodes {
        title
        content
        related_posts {
          nodes {
            title
            slug
            uri
          }
        }
      }
    }
  }
`

Note that we are using the Link component, which allows us to take full advantage of the speed and optimization of the Gatsby generator.

Conclusion

Done! After installing the YARPP plugin, we integrated it with GraphQL queries through a few simple lines of code. In conclusion, we were able to add related posts to our Gatsby WordPress site.

External Resources:

If you like our post, please share it: