Get a peek at our latest innovations at Sanity Product Day on Dec 8th →

Related Content

By Josh Lind

Suggest relevant content based on category tags.


exports.createSchemaCustomization = ({ actions, schema }) => {
      interfaces: ["Node"],
      name: "SanityPost",
      fields: {
        relatedPosts: {
          type: "[SanityPost]",
          resolve: async (source, args, context, info) => {
            const categories = source._rawDataCategories
              ? => 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:
              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...


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