Headless WordPress + Astro:终极组合,打造超快速站点

发布: (2025年12月7日 GMT+8 01:59)
5 min read
原文: Dev.to

Source: Dev.to

介绍

我们都遇到过这种情况:客户想要 WordPress 的编辑便利性,但作为开发者,你追求开发体验(DX)和现代框架(如 Astro)的性能。
解决方案是 Headless WordPress:将前端解耦,使用 Astro 渲染内容,得到一个超快的静态站点,在 Lighthouse 中获得满分,同时为客户保留熟悉的后台管理界面。

为什么选择这两者组合?

  • WordPress(后端):全球使用最广的 CMS,拥有强大的用户、媒体和内容管理功能。
  • Astro(前端):基于 Islands Architecture 的框架,默认向客户端发送 0 KB 的 JavaScript。速度惊人。

第一步:配置后端(WordPress)

  1. 安装 LocalWP 并创建一个新站点。
  2. 插件 > 安装插件 中,安装并激活:
    • WPGraphQL(必装):提供干净、快速的 GraphQL API。
    • WPGraphQL CORS(推荐):当前端请求数据时避免 CORS 阻塞。

激活后,你会在侧边栏看到 GraphQL 选项卡。默认的端点是:

http://tusitio.local/graphql

第二步:初始化 Astro

npm create astro@latest mi-blog-headless
cd mi-blog-headless
npm install

选择 Empty 模板,以获得最小化的起始项目。

第三步:获取文章(首页)

编辑 src/pages/index.astro,将内容替换为下面的代码:

---
const query = `
  query GetPosts {
    posts {
      nodes {
        databaseId
        title
        slug
        excerpt
      }
    }
  }
`;

const response = await fetch("http://tusitio.local/graphql", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ query }),
});

const json = await response.json();
const posts = json.data.posts.nodes;
---

<main>
  <h1>Mi Blog Headless</h1>

  <section>
    <h2>Últimas Entradas 🚀</h2>

    {posts.map((post) => (
      <article>
        <h3>{post.title}</h3>
        <p innerHTML={post.excerpt}></p>
        <a href={`/post/${post.slug}`}>Leer más &rarr;</a>
      </article>
    ))}
  </section>
</main>

注意:http://tusitio.local/graphql 替换为你本地 WordPress 实际的 URL。

第四步:动态路由(文章详情)

创建文件 src/pages/post/[slug].astro

---
// src/pages/post/[slug].astro

export async function getStaticPaths() {
  const response = await fetch("http://tusitio.local/graphql", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      query: `
        query GetSlugs {
          posts {
            nodes {
              slug
            }
          }
        }
      `,
    }),
  });

  const json = await response.json();
  const posts = json.data.posts.nodes;

  return posts.map((post) => ({
    params: { slug: post.slug },
  }));
}

// 获取当前 slug
const { slug } = Astro.params;

const response = await fetch("http://tusitio.local/graphql", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    query: `
      query GetPostBySlug($slug: ID!) {
        post(id: $slug, idType: SLUG) {
          title
          content
          date
        }
      }
    `,
    variables: { slug },
  }),
});

const json = await response.json();
const post = json.data.post;
---

<article>
  <h1>{post.title}</h1>

  <nav>
    <a href="/">← Volver al inicio</a>
  </nav>

  <p>Publicado el: {new Date(post.date).toLocaleDateString()}</p>

  <section innerHTML={post.content}></section>
</article>

结果

  • 运行 npm run dev 查看文章列表并即时跳转到详情页。
  • 准备上线时,执行 npm run build。Astro 会在 dist/ 目录生成静态 .html 文件,可部署到 Vercel、Netlify 或任意静态托管平台。

这种架构的优势

  • 安全性: WordPress 可以隐藏、设密码或放在私有网络中。只有构建过程需要访问它。
  • 速度: 直接提供纯 HTML;访问时不再查询数据库。
  • 可扩展性: 静态站点可以支撑数百万访问而不崩溃。

接下来怎么办?

  • 使用 ACF 为 API 添加自定义字段。
  • 安装 @astrojs/image 优化来自 WordPress 的图片。
  • 在 WordPress 中配置 webhook,让 Vercel(或其他平台)在发布新文章时自动重新构建站点。

常见问题:Headless 模式下是否需要付费的 WordPress 主机?

简短回答: 不需要,没必要使用昂贵的主机。

1. 流量解耦

  • 在传统的 WordPress 单体架构中,每一次访问都会执行 PHP 并查询数据库。
  • 在 Headless 架构中,静态站点(Astro)通过 CDN 承担所有访问流量,WordPress 完全不接受公开访问。只有在编辑或构建时才会被调用。

2. 经济实惠的 WordPress 主机

  • 你可以把 WordPress 部署在最便宜的方案上(甚至本地 Docker 容器或低配 VPS)。
  • 由于几乎没有外部访问,不需要 Nginx 优化、Redis 或大量内存等高级资源。

3. 成本对比

场景传统托管Headless(Astro)
10 次访问/秒低价主机(≈ 5 €/月)静态 CDN(免费)
100 次访问/秒VPS(≈ 50 €/月)静态 CDN(免费)
1 000+ 次访问/秒高成本扩容静态 CDN(免费)

总之,通过前后端解耦,你可以显著降低基础设施成本,同时保持高性能和安全性。

Back to Blog

相关文章

阅读更多 »