文章目录
- WPGraphQL(WordPress插件): 将WordPress REST API替换为GraphQL 按需查询数据(避免over-fetching) 单次请求获取多层嵌套数据(文章+作者+评论+分类) 类型安全(TypeScript生成)
- | 对比项 | REST API | GraphQL (WPGraphQL) | |--------|----------|----------------------| | 请求次数 | 多次(/posts, /users, /comments) | 单次(所有数据一次获取) | | 数据过量 | 是(返回所有字段) | 否(只取需要的字段) | | 类型安全 | 无 | 有(自动生成TypeScript类型) | | 文档 | 手动编写 | 自动生成(GraphiQL) |
- # GraphiQL中执行 query GetPosts { posts(first: 10) { nodes { id title slug date excerpt author { node { name } } categories { nodes { name } } } } }
- query GetPost($slug: String!) { postBy(slug: $slug) { title content date modified author { node { name } } featuredImage { node { sourceUrl(size: MEDIUM) altText } } } }
- query GetCategories { categories(first: 20) { nodes { name slug count # 文章数量 posts(first: 5) { nodes { title slug } } } } }
- npm install @apollo/client graphql
- // lib/apollo-client.ts import { ApolloClient, InMemoryCache } from '@apollo/client'; const client = new ApolloClient({ uri: 'https://www.shenma98.com/graphql', cache: new InMemoryCache(), }); export default client;
- // app/posts/page.tsx 'use client'; import { gql, useQuery } from '@apollo/client'; import client from '@/lib/apollo-client'; const GET_POSTS = gql` query GetPosts { posts(first: 10) { nodes { id title slug excerpt } } } `; export default function PostsPage() { const { loading, error, data } = useQuery(GET_POSTS, { client }); if (loading) return 加载中...; if (error) return 错误: {error.message}; return (
-
- // WordPress安装WPGraphQL JWT Authentication插件 // 插件 → 安装插件 → 搜索"WPGraphQL JWT Authentication" // 登录获取token mutation Login { login(input: { username: "admin", password: "password" }) { authToken refreshToken } }
- mutation CreatePost($token: String!) { createPost(input: { clientMutationId: "CreatePost" title: "新文章标题" content: "文章正文内容" status: PUBLISH }) { post { id title slug } } } // 前端调用(带认证) const CREATE_POST = gql` mutation CreatePost($title: String!, $content: String!) { createPost(input: { title: $title, content: $content, status: PUBLISH }) { post { id title } } } `; const [createPost] = useMutation(CREATE_POST, { context: { headers: { Authorization: `Bearer ${token}`, }, }, });
-
- query GetPostsByCategory($categorySlug: String!) { posts(first: 10, where: { categorySlug: $categorySlug }) { nodes { title slug } } }
- query GetPosts($after: String) { posts(first: 10, after: $after) { nodes { title slug } pageInfo { hasNextPage endCursor } } }
- // 使用DataLoader避免N+1查询 import DataLoader from 'dataloader'; const userLoader = new DataLoader(async (userIds) => { const users = await client.query({ query: gql` query GetUsers($ids: [ID!]!) { users(where: { in: $ids }) { nodes { id name } } } `, variables: { ids: userIds }, }); return users.data.users.nodes; }); // 使用 const author = await userLoader.load(post.authorId);
-
- // WordPress安装WPGraphQL Persisted Queries插件 // 插件 → 安装插件 → 搜索"WPGraphQL Persisted Queries" // 前端:只发送查询ID(不发送完整查询字符串) const queryMap = { 'GetPosts': ` query GetPosts { posts(first: 10) { nodes { title slug } } } `, }; // 发送请求(只发送ID) fetch('https://www.shenma98.com/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ extensions: { persistedQuery: { version: 1, sha256Hash: 'abc123...', // 查询的哈希 }, }, }), });
- // Apollo Client自动缓存(InMemoryCache) const client = new ApolloClient({ uri: 'https://www.shenma98.com/graphql', cache: new InMemoryCache({ typePolicies: { Post: { // 按URI缓存(/post/slug) fields: { content: { merge: true, // 合并分页结果 }, }, }, }, }), });
- | 场景 | 是否使用WPGraphQL | 理由 | |------|---------------------|------| | Headless WordPress + React/Vue | ✅ 强烈推荐 | 单次请求获取所有数据 | | 移动App后端 | ✅ 推荐 | GraphQL适合移动端(减少流量) | | 简单博客(传统主题) | ❌ 不推荐 | REST API足够 | | 实时数据(WebSocket) | ⚠️ 考虑REST + WebSocket | GraphQL无原生实时 |
- WPGraphQL让WordPress成为真正的Headless CMS。2026年,GraphQL已成为前后端分离项目的标配。 立即行动:安装WPGraphQL插件,在GraphiQL中编写你的第一个查询!
本文详解如何使用WPGraphQL将WordPress变为Headless CMS,配合前端框架构建高性能网站。
WPGraphQL(WordPress插件):
- 将WordPress REST API替换为GraphQL
- 按需查询数据(避免over-fetching)
- 单次请求获取多层嵌套数据(文章+作者+评论+分类)
- 类型安全(TypeScript生成)
| 对比项 | REST API | GraphQL (WPGraphQL) |
|--------|----------|----------------------|
| 请求次数 | 多次(/posts, /users, /comments) | 单次(所有数据一次获取) |
| 数据过量 | 是(返回所有字段) | 否(只取需要的字段) |
| 类型安全 | 无 | 有(自动生成TypeScript类型) |
| 文档 | 手动编写 | 自动生成(GraphiQL) |
# 方法一:WordPress后台安装
composer require wp-graphql/wp-graphql
WPGraphQL内置GraphiQL IDE:
- WordPress后台 → GraphQL
- 打开GraphiQL Interactive(交互式调试)
- 编写并测试GraphQL查询
# GraphiQL中执行
query GetPosts {
posts(first: 10) {
nodes {
id
title
slug
date
excerpt
author {
node {
name
}
}
categories {
nodes {
name
}
}
}
}
}
query GetPost($slug: String!) {
postBy(slug: $slug) {
title
content
date
modified
author {
node {
name
}
}
featuredImage {
node {
sourceUrl(size: MEDIUM)
altText
}
}
}
}
query GetCategories {
categories(first: 20) {
nodes {
name
slug
count # 文章数量
posts(first: 5) {
nodes {
title
slug
}
}
}
}
}
npm install @apollo/client graphql
// lib/apollo-client.ts
import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://www.shenma98.com/graphql',
cache: new InMemoryCache(),
});
export default client;
// app/posts/page.tsx
'use client';
import { gql, useQuery } from '@apollo/client';
import client from '@/lib/apollo-client';
const GET_POSTS = gql`
query GetPosts {
posts(first: 10) {
nodes {
id
title
slug
excerpt
}
}
}
`;
export default function PostsPage() {
const { loading, error, data } = useQuery(GET_POSTS, { client });
if (loading) return
加载中...
;
if (error) return
错误: {error.message}
;
return (
{data.posts.nodes.map((post: any) => (
-
))}
);
}
// app/posts/[slug]/page.tsx
import { gql } from 'graphql-tag';
import client from '@/lib/apollo-client';
async function getPost(slug: string) {
const { data } = await client.query({
query: gql`
query GetPost($slug: String!) {
postBy(slug: $slug) {
title
content
date
}
}
`,
variables: { slug },
});
return data.postBy;
}
export default async function PostPage({ params }: { params: { slug: string } }) {
const post = await getPost(params.slug);
return (

评论(0)