文章目录
  • composer require wp-graphql/wp-graphql
  • {data.posts.nodes.map((post: any) => ( {post.title} ))} ); }
  • {post.date} ); } export const revalidate = 60; // ISR: 60秒重新验证
  • 本文详解如何使用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 (