#need select post by desc pubdate

3 messages · Page 1 of 1 (latest)

pseudo valley
#

export async function getStaticPaths({ paginate }) {
const allPosts = Object.values(
import.meta.glob('../../md/blog/*.md', { eager: true })
)
return paginate(allPosts, { pageSize: 6 })
}

proven saddleBOT
#

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:

  1. Collects all your Markdown files using import.meta.glob()
  2. Sorts them by comparing the pubDate property in the frontmatter of each post
  3. Uses the JavaScript sort() method with a comparison function that subtracts dates to get descending order (newest first)
  4. 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.

Make sure your Markdown files have a pubDate property in their frontmatter. If your date field has a different name, adjust the sorting function accordingly.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: