How to Add Related Content for Sanity.io

Sanity.io stands out as a modern, headless CMS that treats content as data, offering flexible and powerful ways to manage, query, and present your digital content. An essential feature in any content-rich application is the ability to display related content. This enhances user engagement, improves SEO, and keeps readers on your site longer. In this article, we'll learn how to add related content in Sanity.io, focusing on schema setup, querying with GROQ, and integrating with your frontend. We will also look at how Wisp CMS leverages AI to suggest related articles automatically.

Introduction to Related Content in Sanity.io

Displaying related content involves showing users additional articles, posts, or items that are contextually similar to the one they are currently viewing. This method not only helps in keeping users engaged but also improves the overall content discoverability on your site.

  • Benefits of Related Content:

    • Improved User Engagement: Readers are more likely to stay on your site when they find more content related to their interests.

    • SEO Boost: Internal linking to related content helps search engines understand the structure and relevance of your content.

    • Revenue Opportunities: For e-commerce sites, showing related products can increase sales.

Setting Up Your Sanity.io Schema:

To begin adding related content, you need to define your schema types in Sanity.io. The schema in Sanity.io defines the structure of the content that can be created and edited within the Sanity Studio.

Overview of Schema Types:

Sanity.io supports various schema types including array, block, boolean, date, datetime, document, file, geopoint, image, number, object, reference, slug, string, span, text, and url. Here’s a breakdown of a basic schema setup demonstrating how to integrate related content:

Basic Schema Example:
import { defineConfig } from 'sanity'

export default defineConfig({
  schema: {
    types: [
      {
        title: "Blog Post",
        name: "blogPost",
        type: "document",
        fields: [
          {
            title: "Title",
            name: "title",
            type: "string"
          },
          {
            title: "Related Posts",
            name: "relatedPosts",
            type: "array",
            of: [{ type: "reference", to: {type: "blogPost"} }]
          }
        ]
      }
    ]
  }
})

Best Practices:

  • Organizing Schema Types: Keep the types array in a separate file for better organization.

  • Using Helper Functions: Utilize helper functions like defineType, defineField, and defineArrayMember to enhance type safety and IDE support.

Querying Related Content Using GROQ:

GROQ (Graph-Relational Object Queries) is Sanity.io's powerful query language designed for precise content fetching. It lets you specify the exact information your application needs.

Writing GROQ Queries for Related Content:

Basic Query Structure:
*[_type == 'blogPost' && _id == $id]{
  title,
  "relatedPosts": relatedPosts[]->{
    title,
    slug
  }
}

This query fetches a blog post by its ID and includes related posts by expanding the reference array.

Advanced Queries:

Expanding References:

*[_type == 'blogPost' && _id == $id]{
  title,
  "relatedPosts": relatedPosts[]->{
    title,
    "authorName": author->name
  }
}
Filtering by References:
*[_type == 'blogPost' && references($currentPostId)]

Joining Data:

Using joins, you can fetch related data efficiently:

*[_type == "author"]{
  _id,
  name,
  "posts": *[_type == "blogPost" && references(^._id)].title
}

Best Practices:

  • Optimizing Queries: Reduce loading time by combining queries into one and limiting fields to necessary ones.

  • Using Projections: Specify exactly which fields you want to retrieve to avoid unnecessary data fetching.

Integrating Related Content in Your Frontend:

Once you have defined your schema and written your GROQ queries, the next step is to fetch and display this data in your frontend.

Fetching Data from Sanity.io:

Here’s an example using a JavaScript frontend framework:

import client from '@sanity/client'

const sanityClient = client({
  projectId: 'yourProjectId',
  dataset: 'yourDataset',
  useCdn: true
})

const fetchBlogPost = async (postId) => {
  const query = `*[_type == 'blogPost' && _id == $id]{
    title,
    "relatedPosts": relatedPosts[]->{
      title,
      slug
    }
  }`
  const params = { id: postId }
  return await sanityClient.fetch(query, params)
}

Displaying Related Content:

Using a framework like React:

const BlogPost = ({ postId }) => {
  const { data, error } = useSWR(`/api/fetchPost?postId=${postId}`, fetchBlogPost)

  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>

  return (
    <div>
      <h1>{data.title}</h1>
      <h2>Related Posts:</h2>
      <ul>
        {data.relatedPosts.map(post => (
          <li key={post.slug}>{post.title}</li>
        ))}
      </ul>
    </div>
  )
}

Best Practices for Related Content Retrieval:

Optimizing Queries:

  • Performance Considerations: Write efficient queries and avoid fetching unnecessary fields.

  • Combined Queries: Use combined queries where possible to reduce the number of requests.

Improving User Experience:

  • Relevance: Ensure that related content is contextually relevant.

  • UI/UX Design: Design the related content section to be visually appealing and easy to navigate.

Case Study: Wisp CMS's AI-Powered Related Content:

Overview of Wisp's Related Content Feature:

Wisp CMS uses AI to automate the suggestion of related articles. This feature leverages OpenAI's embedding model to understand and interpret the semantic relationships between articles.

Benefits:

  • For Creators: Eliminates the need for manual linking, saving time and effort.

  • For Users: Offers personalized content recommendations, enhancing the reading experience.

  • For Marketers: Increases user engagement, time spent on site, and reduces bounce rates.

Implementation Insights:

Wisp transforms each blog post into a numerical vector representation, allowing it to analyze and compare articles effectively. This semantic analysis ensures that the most relevant articles are suggested to the reader.

Conclusion

Adding related content to your Sanity.io application not only enhances user experience but also contributes to better site performance and user retention. By setting up an appropriate schema, writing efficient GROQ queries, and integrating this data with your frontend, you can effectively display related content. Additionally, leveraging AI solutions like those in Wisp CMS can further automate and optimize this process.

Interested in AI-powered related content suggestions?

Learn more about how Wisp CMS can enhance your content strategy by visiting Wisp's Related Blog Post Feature.

8/12/2024
Related Posts
How to Add Related Content for Payload CMS

How to Add Related Content for Payload CMS

Discover how Payload CMS's Relationship fields can streamline your content management and elevate user experience seamlessly.

Read Full Story
Understanding Relationships in Payload CMS

Understanding Relationships in Payload CMS

Master Payload CMS relationships: From basic configs to advanced use cases. Discover how to build complex content architectures that elevate your web projects.

Read Full Story
How to Add Related Content for Strapi

How to Add Related Content for Strapi

Discover how to add related content to your Strapi project. From one-to-one to polymorphic relations, this guide has you covered with practical steps & advanced techniques.

Read Full Story