Skip to content

Instead of _embed and breaking the posts to pages for pagination, actually handle pagination on the WP API level #42

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .env.example

This file was deleted.

62 changes: 21 additions & 41 deletions app/posts/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import { FilterPosts } from "@/components/posts/filter";
import { SearchInput } from "@/components/posts/search-input";

import type { Metadata } from "next";
import { Button } from "@/components/ui/button";
import Link from "next/link";

export const metadata: Metadata = {
title: "Blog Posts",
Expand All @@ -46,23 +48,17 @@ export default async function Page({
const params = await searchParams;
const { author, tag, category, page: pageParam, search } = params;

const page = pageParam ? parseInt(pageParam, 10) : 1;
const postsPerPage = 3;

// Fetch data based on search parameters
const [posts, authors, tags, categories] = await Promise.all([
getAllPosts({ author, tag, category, search }),
getAllPosts({ author, tag, category, search, page: page, perPage: postsPerPage }),
search ? searchAuthors(search) : getAllAuthors(),
search ? searchTags(search) : getAllTags(),
search ? searchCategories(search) : getAllCategories(),
]);

// Handle pagination
const page = pageParam ? parseInt(pageParam, 10) : 1;
const postsPerPage = 9;
const totalPages = Math.ceil(posts.length / postsPerPage);
const paginatedPosts = posts.slice(
(page - 1) * postsPerPage,
page * postsPerPage
);

// Create pagination URL helper
const createPaginationUrl = (newPage: number) => {
const params = new URLSearchParams();
Expand All @@ -73,15 +69,14 @@ export default async function Page({
if (search) params.set("search", search);
return `/posts${params.toString() ? `?${params.toString()}` : ""}`;
};

return (
<Section>
<Container>
<div className="space-y-8">
<Prose>
<h2>All Posts</h2>
<p className="text-muted-foreground">
{posts.length} {posts.length === 1 ? "post" : "posts"} found
{posts.total} {posts.total === 1 ? "post" : "posts"} found
{search && " matching your search"}
</p>
</Prose>
Expand All @@ -99,9 +94,9 @@ export default async function Page({
/>
</div>

{paginatedPosts.length > 0 ? (
{posts.posts.length > 0 ? (
<div className="grid md:grid-cols-3 gap-4">
{paginatedPosts.map((post) => (
{posts.posts.map((post) => (
<PostCard key={post.id} post={post} />
))}
</div>
Expand All @@ -111,33 +106,18 @@ export default async function Page({
</div>
)}

{totalPages > 1 && (
<Pagination>
<PaginationContent>
<PaginationItem>
<PaginationPrevious
className={
page <= 1 ? "pointer-events-none opacity-50" : ""
}
href={createPaginationUrl(page - 1)}
/>
</PaginationItem>
<PaginationItem>
<PaginationLink href={createPaginationUrl(page)}>
{page}
</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationNext
className={
page >= totalPages ? "pointer-events-none opacity-50" : ""
}
href={createPaginationUrl(page + 1)}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
)}
{/* Pagination */}
{(posts && posts.pages > 1) && <section className='text-white flex flex-row w-fit mx-auto'>
<section className='flex flex-row gap-3'>
<Button variant={"ghost"} asChild><Link className={`lg:w-full hover:bg-gray-700/60 ${page === 1 ? 'dark:bg-gray-700 bg-blue-100 !text-primary' : ''}`} href={createPaginationUrl(1)}>۱</Link></Button>
{page > 3 && "..."}
{page-1 > 1 && <Button variant={"ghost"} asChild><Link href={createPaginationUrl(page - 1)} className={`lg:w-full hover:bg-gray-700/60`}>{(page-1)}</Link></Button>}
{page != 1 && page != posts.pages && <Button variant={"ghost"} asChild><p className={`lg:w-full hover:bg-gray-700/60 dark:bg-gray-700 bg-blue-100 !text-primary`}>{(page)}</p></Button>}
{page+1 < posts.pages && <Button variant={"ghost"} asChild><Link href={createPaginationUrl(page + 1)} className={`lg:w-full hover:bg-gray-700/60`}>{(page+1)}</Link></Button>}
{page < posts.pages-2 && "..."}
<Button variant={"ghost"} asChild><Link className={`lg:w-full hover:bg-gray-700/60 ${page === posts.pages ? 'dark:bg-gray-700 bg-blue-100 !text-primary' : ''}`} href={createPaginationUrl(posts.pages)}>{(posts.pages)}</Link></Button>
</section>
</section>}
</div>
</Container>
</Section>
Expand Down
81 changes: 51 additions & 30 deletions lib/wordpress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ class WordPressAPIError extends Error {
async function wordpressFetch<T>(
url: string,
options: FetchOptions = {}
): Promise<T> {
): Promise<{
data: unknown,
headers: Headers
}> {
const userAgent = "Next.js WordPress Client";

const response = await fetch(url, {
Expand All @@ -73,7 +76,10 @@ async function wordpressFetch<T>(
);
}

return response.json();
return ({
data: await response.json(),
headers: response.headers
})
}

// WordPress Functions
Expand All @@ -83,10 +89,19 @@ export async function getAllPosts(filterParams?: {
tag?: string;
category?: string;
search?: string;
}): Promise<Post[]> {
page?: number;
perPage?: number;
news?: boolean
}): Promise<{
posts: Post[],
pages: number,
total: number,
}> {
const query: Record<string, any> = {
_embed: true,
per_page: 100,
// _embed: true,
// per_page: 100,
per_page: filterParams?.perPage || 9,
page: filterParams?.page || 1,
};

if (filterParams?.search) {
Expand Down Expand Up @@ -117,12 +132,18 @@ export async function getAllPosts(filterParams?: {
}

const url = getUrl("/wp-json/wp/v2/posts", query);
return wordpressFetch<Post[]>(url, {
const data = await wordpressFetch(url, {
next: {
...defaultFetchOptions.next,
tags: ["wordpress", "posts"],
tags: ["wordpress", "authors"],
},
});
})

return ({
posts: data.data,
pages: Number(data.headers.get('x-wp-totalpages')),
total: Number(data.headers.get('x-wp-total'))
})
}

export async function getPostById(id: number): Promise<Post> {
Expand All @@ -134,7 +155,7 @@ export async function getPostById(id: number): Promise<Post> {
},
});

return response;
return response.data;
}

export async function getPostBySlug(slug: string): Promise<Post> {
Expand All @@ -146,7 +167,7 @@ export async function getPostBySlug(slug: string): Promise<Post> {
},
});

return response[0];
return response.data[0];
}

export async function getAllCategories(): Promise<Category[]> {
Expand All @@ -158,7 +179,7 @@ export async function getAllCategories(): Promise<Category[]> {
},
});

return response;
return response.data;
}

export async function getCategoryById(id: number): Promise<Category> {
Expand All @@ -170,7 +191,7 @@ export async function getCategoryById(id: number): Promise<Category> {
},
});

return response;
return response.data;
}

export async function getCategoryBySlug(slug: string): Promise<Category> {
Expand All @@ -182,7 +203,7 @@ export async function getCategoryBySlug(slug: string): Promise<Category> {
},
});

return response[0];
return response.data[0];
}

export async function getPostsByCategory(categoryId: number): Promise<Post[]> {
Expand All @@ -194,7 +215,7 @@ export async function getPostsByCategory(categoryId: number): Promise<Post[]> {
},
});

return response;
return response.data;
}

export async function getPostsByTag(tagId: number): Promise<Post[]> {
Expand All @@ -206,7 +227,7 @@ export async function getPostsByTag(tagId: number): Promise<Post[]> {
},
});

return response;
return response.data;
}

export async function getTagsByPost(postId: number): Promise<Tag[]> {
Expand All @@ -218,7 +239,7 @@ export async function getTagsByPost(postId: number): Promise<Tag[]> {
},
});

return response;
return response.data;
}

export async function getAllTags(): Promise<Tag[]> {
Expand All @@ -230,7 +251,7 @@ export async function getAllTags(): Promise<Tag[]> {
},
});

return response;
return response.data;
}

export async function getTagById(id: number): Promise<Tag> {
Expand All @@ -242,7 +263,7 @@ export async function getTagById(id: number): Promise<Tag> {
},
});

return response;
return response.data;
}

export async function getTagBySlug(slug: string): Promise<Tag> {
Expand All @@ -254,7 +275,7 @@ export async function getTagBySlug(slug: string): Promise<Tag> {
},
});

return response[0];
return response.data[0];
}

export async function getAllPages(): Promise<Page[]> {
Expand All @@ -266,7 +287,7 @@ export async function getAllPages(): Promise<Page[]> {
},
});

return response;
return response.data;
}

export async function getPageById(id: number): Promise<Page> {
Expand All @@ -278,7 +299,7 @@ export async function getPageById(id: number): Promise<Page> {
},
});

return response;
return response.data;
}

export async function getPageBySlug(slug: string): Promise<Page> {
Expand All @@ -290,7 +311,7 @@ export async function getPageBySlug(slug: string): Promise<Page> {
},
});

return response[0];
return response.data[0];
}

export async function getAllAuthors(): Promise<Author[]> {
Expand All @@ -302,7 +323,7 @@ export async function getAllAuthors(): Promise<Author[]> {
},
});

return response;
return response.data;
}

export async function getAuthorById(id: number): Promise<Author> {
Expand All @@ -314,7 +335,7 @@ export async function getAuthorById(id: number): Promise<Author> {
},
});

return response;
return response.data;
}

export async function getAuthorBySlug(slug: string): Promise<Author> {
Expand All @@ -326,7 +347,7 @@ export async function getAuthorBySlug(slug: string): Promise<Author> {
},
});

return response[0];
return response.data[0];
}

export async function getPostsByAuthor(authorId: number): Promise<Post[]> {
Expand All @@ -338,7 +359,7 @@ export async function getPostsByAuthor(authorId: number): Promise<Post[]> {
},
});

return response;
return response.data;
}

export async function getPostsByAuthorSlug(
Expand All @@ -353,7 +374,7 @@ export async function getPostsByAuthorSlug(
},
});

return response;
return response.data;
}

export async function getPostsByCategorySlug(
Expand All @@ -368,7 +389,7 @@ export async function getPostsByCategorySlug(
},
});

return response;
return response.data;
}

export async function getPostsByTagSlug(tagSlug: string): Promise<Post[]> {
Expand All @@ -381,7 +402,7 @@ export async function getPostsByTagSlug(tagSlug: string): Promise<Post[]> {
},
});

return response;
return response.data;
}

export async function getFeaturedMediaById(id: number): Promise<FeaturedMedia> {
Expand All @@ -393,7 +414,7 @@ export async function getFeaturedMediaById(id: number): Promise<FeaturedMedia> {
},
});

return response;
return response.data;
}

// Helper function to search across categories
Expand Down
Loading