Home / Log
As your blog grows, you might want to incorporate different types of content, such as guest posts, alongside your regular posts. Astro makes this process straightforward, allowing you to maintain multiple collections while presenting a unified blog experience to your readers. In this tutorial, we’ll walk through the process of integrating both regular posts and guest posts into your Astro blog.
Before we dive into the code, ensure you have two collections set up in your src/content
directory:
posts
: Your regular blog postsguestposts
: Posts written by guest authorsThe key to integrating multiple collections lies in updating your /src/pages/blog/[...slug].astro
file. Here’s how to do it:
Start by importing both collections at the top of your file:
---
import { getCollection } from 'astro:content'
const posts = await getCollection('posts')
const guestPosts = await getCollection('guestposts')
---
Next, merge the two collections into a single array:
---
const allPosts = [...posts, ...guestPosts]
---
Modify the getStaticPaths
function to use the combined collection:
---
export async function getStaticPaths() {
const allPosts = [...posts, ...guestPosts]
return allPosts.map((post) => ({
params: { slug: post.slug },
props: { post },
}))
}
const { post } = Astro.props
---
Finally, render the post content as usual:
---
const { Content } = await post.render()
---
<html>
<head>
<title>{post.data.title}</title>
</head>
<body>
<h1>{post.data.title}</h1>
<Content />
</body>
</html>
To differentiate between regular and guest posts, you can add a conditional check:
---
const postType = post.collection === 'guestposts' ? 'Guest Post' : 'Regular Post'
---
<p>This is a {postType}</p>
Ensure consistent sorting across all posts by using a common frontmatter property:
---
const allPosts = [...posts, ...guestPosts].sort(
(a, b) => new Date(b.data.pubDate) - new Date(a.data.pubDate)
)
---
By following these steps, you can easily integrate multiple post collections into your Astro blog. This approach allows you to maintain separate content sources while presenting a unified blog experience to your readers. As your blog continues to grow, you can add more collections and adapt this method to suit your evolving needs.
Remember to update your blog index page and any other relevant components to reflect these changes. Happy blogging with Astro!