👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Related Content

By Josh Lind

Suggest relevant content based on category tags.

gatsby-node.js

exports.createSchemaCustomization = ({ actions, schema }) => {
  actions.createTypes([
    schema.buildObjectType({
      interfaces: ["Node"],
      name: "SanityPost",
      fields: {
        relatedPosts: {
          type: "[SanityPost]",
          resolve: async (source, args, context, info) => {
            const categories = source._rawDataCategories
              ? source._rawDataCategories.map((c) => c._ref)
              : [];
            if (!categories.length) return [];

            const posts = await context.nodeModel.runQuery({
              query: {
                filter: {
                  categories: {
                    elemMatch: {
                      _id: { in: categories },
                    },
                  },
                  // exclude current node
                  _id: { ne: source._id },
                },
                sort: {
                  fields: ["publishedAt"],
                  order: ["DESC"],
                },
                // no way to limit results in runQuery
                // see: https://github.com/gatsbyjs/gatsby/issues/15453
              },
              type: "SanityPost",
            });

            return posts && posts.length > 0 ? posts : [];
          },
        },
      },
    })
  ]);
};

You may already be generating category pages (listing posts referencing a given category tag). But the other side can be tricky.

Then be sure to put relatedPosts into your page query as if it was another field (with subfields of course).

NOTE: You must use _rawDataCategories in your query to get the id via _ref otherwise it’s that reference is a hash instead.

Credit to for plenty of this solution, though it needed some updates... https://nimblewebdeveloper.com/blog/gatsby-generate-related-posts-at-build-time

Contributor

Josh Lind

Build it to be explored, the value is the flexibility. Don't get obsolete.

Josh is located at Seattle, WA
Visit Josh Lind's profile