本文详解如何使用WPGraphQL将WordPress变为Headless CMS,配合前端框架构建高性能网站。
什么是WPGraphQL
WPGraphQL(WordPress插件):
- 将WordPress REST API替换为GraphQL
- 按需查询数据(避免over-fetching)
- 单次请求获取多层嵌套数据(文章+作者+评论+分类)
- 类型安全(TypeScript生成)
为什么用GraphQL替代REST API
| 对比项 | REST API | GraphQL (WPGraphQL) |
|--------|----------|----------------------|
| 请求次数 | 多次(/posts, /users, /comments) | 单次(所有数据一次获取) |
| 数据过量 | 是(返回所有字段) | 否(只取需要的字段) |
| 类型安全 | 无 | 有(自动生成TypeScript类型) |
| 文档 | 手动编写 | 自动生成(GraphiQL) |
实战一:安装与配置WPGraphQL
安装插件
# 方法一:WordPress后台安装
插件 → 安装插件 → 搜索"WPGraphQL" → 安装并激活
方法二:Composer安装(开发者)
composer require wp-graphql/wp-graphql
启用GraphiQL(调试工具)
WPGraphQL内置GraphiQL IDE:
- WordPress后台 → GraphQL
- 打开GraphiQL Interactive(交互式调试)
- 编写并测试GraphQL查询
实战二:基础查询(Query)
查询文章列表
# GraphiQL中执行
query GetPosts {
posts(first: 10) {
nodes {
id
title
slug
date
excerpt
author {
node {
name
}
}
categories {
nodes {
name
}
}
}
}
}
查询单个文章(按Slug)
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
}
}
}
}
}
实战三:前端集成(Next.js + WPGraphQL)
安装Apollo Client
npm install @apollo/client graphql
配置Apollo Client
// 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;
查询文章列表(Next.js)
// 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) => (
-
))}
);
}
查询文章详情(带ISG)
// 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 (
{post.title}

评论(0)