#need select post by desc pubdate
3 messages · Page 1 of 1 (latest)
Hi @pseudo valley. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To sort your blog posts by publication date in descending order, you need to modify your getStaticPaths function to sort the array of posts before passing it to the paginate function. Here's how you can do it:
export async function getStaticPaths({ paginate }) {
const allPosts = Object.values(
import.meta.glob('../../md/blog/*.md', { eager: true })
);
// Sort posts by publication date in descending order
const sortedPosts = allPosts.sort((a, b) => {
return new Date(b.frontmatter.pubDate) - new Date(a.frontmatter.pubDate);
});
return paginate(sortedPosts, { pageSize: 6 });
}
This code:
- Collects all your Markdown files using
import.meta.glob() - Sorts them by comparing the
pubDateproperty in the frontmatter of each post - Uses the JavaScript
sort()method with a comparison function that subtracts dates to get descending order (newest first) - Passes the sorted array to the
paginate()function
The import.meta.glob() function is a powerful Astro feature that allows you to access data from multiple files at once using glob patterns, as explained in the Imports reference documentation.