#pagination
3 messages · Page 1 of 1 (latest)
It looks like you're trying to implement pagination in Astro for WordPress posts. Based on the knowledge sources, I can help you with this implementation.
Astro has built-in pagination support for large collections of data that need to be split across multiple pages. The paginate() function is used to generate these pages from an array of values.
Here's how you can implement pagination for WordPress posts:
---
export async function getStaticPaths({ paginate }) {
// Fetch your WordPress posts
let res = await fetch("your-wordpress-api-endpoint");
let posts = await res.json();
// Define how many posts per page
const postPerPage = 10; // Adjust this number as needed
// Return paginated data
return paginate(posts, { pageSize: postPerPage });
}
// All paginated data is passed on the "page" prop
const { page } = Astro.props;
---
<h1>Page {page.currentPage}</h1>
<!-- Display your posts -->
<ul>
{page.data.map((post) => (
<li>
<a href={`/posts/${post.slug}/`}>{post.title.rendered}</a>
</li>
))}
</ul>
<!-- Navigation -->
{page.url.prev ? <a href={page.url.prev}>Previous</a> : null}
{page.url.next ? <a href={page.url.next}>Next</a> : null}
The page prop provides several useful properties for building your pagination UI:
page.data: The array of posts for the current pagepage.currentPage: The current page numberpage.total: Total number of items across all pagespage.size: Number of items per pagepage.lastPage: Number of the last pagepage.url.prev: URL of the previous page (if there is one)page.url.next: URL of the next page (if there is one)page.url.first: URL of the first pagepage.url.last: URL of the last page
For this to work, your file should be named [page].astro which will generate routes like /posts/1, /posts/2, etc. Alternatively, you can use [...page].astro which will generate /posts, /posts/2, /posts/3, etc. (with the first page at the root).
Note that as of Astro v5, the URLs returned by paginate() automatically include the base value from your Astro config, so you don't need to manually prepend it.