Next.js (App Router) × WordPress API でヘッドレスCMSを構築する方法【wp-types対応】

1. Next.js のセットアップ

まず、Next.js の App Router を利用したプロジェクトを作成し、wp-types をインストールします。

npx create-next-app@latest my-blog
cd my-blog
npm install axios wp-types

2. 記事一覧ページの作成 (app/page.tsx)

WordPress REST API から記事一覧を取得し、リストとして表示します。

2-1. 記事データを取得

import { WP_REST_API_Posts } from "wp-types"; // 型定義を適用
import Link from "next/link";

async function getPosts(): Promise<WP_REST_API_Posts> {
const res = await fetch("https://example.com/wp-json/wp/v2/posts?_embed", {
cache: "no-store",
});
if (!res.ok) {
throw new Error("Failed to fetch posts");
}
return res.json();
}

export default async function Home() {
const posts = await getPosts();

return (
<div>
<h1 className="text-3xl font-bold">ブログ記事一覧</h1>
<ul>
{posts.map((post) => (
<li key={post.id} className="border p-4 my-2">
<Link href={`/post/${post.id}`} className="text-blue-500">
<h2 dangerouslySetInnerHTML={{ __html: post.title.rendered }} />
</Link>
{post._embedded?.["wp:featuredmedia"] && (
<img
src={post._embedded["wp:featuredmedia"][0].source_url}
alt={post._embedded["wp:featuredmedia"][0].alt_text || "記事の画像"}
className="w-full h-auto mt-2"
/>
)}
</li>
))}
</ul>
</div>
);
}

✅ WP_REST_API_Posts を使用し、型安全にデータを取得
✅ _embedded を利用してアイキャッチ画像を取得


3. 記事詳細ページ (app/post/[id]/page.tsx)

詳細ページでは、記事の タイトル・アイキャッチ画像・本文 を表示します。

import { WP_REST_API_Post } from "wp-types";

async function getPost(id: string): Promise<WP_REST_API_Post> {
const res = await fetch(`https://example.com/wp-json/wp/v2/posts/${id}?_embed`, {
cache: "no-store",
});
if (!res.ok) {
throw new Error("Failed to fetch post");
}
return res.json();
}

export default async function PostPage({ params }: { params: { id: string } }) {
const post = await getPost(params.id);

return (
<div>
<h1 className="text-3xl font-bold" dangerouslySetInnerHTML={{ __html: post.title.rendered }} />
{post._embedded?.["wp:featuredmedia"] && (
<img
src={post._embedded["wp:featuredmedia"][0].source_url}
alt={post._embedded["wp:featuredmedia"][0].alt_text || "記事の画像"}
className="w-full h-auto my-4"
/>
)}
<p className="text-sm text-gray-500">
投稿日: {new Date(post.date).toLocaleDateString()} | 著者: {post._embedded?.author?.[0]?.name}
</p>
<div dangerouslySetInnerHTML={{ __html: post.content.rendered }} className="prose" />
</div>
);
}

✅ 記事の詳細ページを動的に取得し、表示
✅ WP_REST_API_Post を適用し、型エラーを防止
✅ 公開日と著者情報を表示


4. ISR (Incremental Static Regeneration) の適用

最新記事を 自動で更新 できるように ISR を導入します。

async function getPosts(): Promise<WP_REST_API_Posts> {
const res = await fetch("https://example.com/wp-json/wp/v2/posts?_embed", {
next: { revalidate: 60 }, // 60秒ごとにデータを再取得
});
return res.json();
}

✅ 60秒ごとに最新の記事データを取得・再生成


5. Tailwind CSS でデザインを適用

記事一覧や詳細ページの見た目を改善するために、Tailwind CSS を適用します。

5-1. Tailwind CSS のインストール

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

5-2. Tailwind の設定 (tailwind.config.js)

/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./app/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {},
},
plugins: [],
};

5-3. グローバル CSS (app/globals.css)

@tailwind base;
@tailwind components;
@tailwind utilities;

✅ 記事リストや詳細ページに適用し、見た目を改善


6. まとめ

本記事では、Next.js (App Router) × WordPress API を活用し、以下の機能を実装しました。

  • ✅ WP_REST_API_Posts を使用し、型安全に記事を取得
  • ✅ WordPress API の _embed を活用し、アイキャッチ画像を取得
  • ✅ ISR (Incremental Static Regeneration) で動的に記事を更新
  • ✅ Tailwind CSS でデザインを整え、視認性を向上

この方法を活用すれば、SEO に強く、高速なヘッドレス WordPress サイトを構築できます!