Skip to content

无头 WordPress 和 Astro

WordPress 是一个内容管理系统,包括自己的前端,但也可以用作无头 CMS 来为你的 Astro 项目提供内容。

¥WordPress is a content management system that includes its own frontend, but can also be used as a headless CMS to provide content to your Astro project.

¥Integrating with Astro

WordPress 附带一个内置的 WordPress REST API,可将你的 WordPress 数据连接到 Astro。你可以选择在你的站点上安装 WPGraphQLGato GraphQL 以使用 GraphQL。

¥WordPress comes with a built-in WordPress REST API to connect your WordPress data to Astro. You can optionally install WPGraphQL or Gato GraphQL on your site to use GraphQL.

¥Prerequisites

首先,你需要具备以下条件:

¥To get started, you will need to have the following:

  1. Astro 项目 - 如果你还没有 Astro 项目,我们的 安装指南 将立即帮助你启动并运行。
  2. 一个 WordPress 网站 - 你网站的 REST API 是 [YOUR_SITE]/wp-json/wp/v2/,默认情况下可用于任何 WordPress 网站。在本地环境中设置 WordPress 也是可以的。

¥Setting up Credentials

默认情况下,你的 WordPress REST API 可用于外部请求来获取数据,而无需进行身份验证。这不允许用户修改你的数据或站点设置,并允许你在没有任何凭据的情况下在 Astro 项目中使用你的数据。

¥Your WordPress REST API is available to external requests for data fetching without authentication by default. This does not allow users to modify your data or site settings and allows you to use your data in your Astro project without any credentials.

如果需要,你可以选择 需要身份验证

¥You may choose to require authentication if necessary.

¥Fetching Data

通过站点的唯一 REST API URL 和内容路径获取 WordPress 数据。(对于博客,这通常是 posts。)然后,你可以使用 Astro 的 set:html={} 指令渲染数据属性。

¥Fetch your WordPress data through your site’s unique REST API URL and the route for your content. (For a blog, this will commonly be posts.) Then, you can render your data properties using Astro’s set:html={} directive.

例如,要显示帖子标题及其内容的列表:

¥For example, to display a list of post titles and their content:

src/pages/index.astro
---
const res = await fetch("https://[YOUR-SITE]/wp-json/wp/v2/posts");
const posts = await res.json();
---
<h1>Astro + WordPress 🚀</h1>
{
posts.map((post) => (
<h2 set:html={post.title.rendered} />
<p set:html={post.content.rendered} />
))
}

WordPress REST API 包括 全局参数,例如 _fields_embed

¥The WordPress REST API includes global parameters such as _fields and _embed.

你可以通过此 API 获得大量数据,因此你可能希望仅获取某些字段。你可以通过将 _fields 参数添加到 API URL 来限制你的响应,例如:[YOUR-SITE]/wp/v2/posts?_fields=author,id,excerpt,title,link

¥A large quantity of data is available to you via this API, so you may wish to only fetch certain fields. You can restrict your response by adding the _fields parameter to the API URL, for example: [YOUR-SITE]/wp/v2/posts?_fields=author,id,excerpt,title,link

API 还可以返回与你的帖子相关的内容,例如父帖子的链接或帖子评论的链接。你可以将 _embed 参数添加到 API URL(例如 [YOUR-SITE]/wp/v2/posts?_embed),以向服务器指示响应应包含这些嵌入资源。

¥The API can also return content related to your post, such as a link to the parent post, or to comments on the post. You can add the _embed parameter to the API URL (e.g. [YOUR-SITE]/wp/v2/posts?_embed) to indicate to the server that the response should include these embedded resources.

使用 WordPress 和 Astro 构建博客

标题部分 使用 WordPress 和 Astro 构建博客

¥Building a blog with WordPress and Astro

此示例从 https://norian.studio/dinosaurs/ 的公共 WordPress API 获取数据。这个 WordPress 网站在 dinos 路由下存储有关单个恐龙的信息,就像博客在 posts 路由下存储单个博客文章一样。

¥This example fetches data from the public WordPress API of https://norian.studio/dinosaurs/. This WordPress site stores information about individual dinosaurs under the dinos route, just as a blog would store individual blog posts under the posts route.

此示例展示了如何在 Astro 中重现此站点结构:列出恐龙的索引页面,以及动态生成的各个恐龙页面的链接。

¥This example shows how to reproduce this site structure in Astro: an index page that lists dinosaurs with links to dynamically-generated individual dinosaur pages.

显示 WordPress 帖子列表

标题部分 显示 WordPress 帖子列表

¥Displaying a list of WordPress posts

src/pages/index.astro 页列出了每种恐龙,并附有说明和指向其自己页面的链接。

¥The page src/pages/index.astro lists each dinosaur, with a description and link to its own page.

  • Directorysrc/
    • Directorypages/
      • index.astro
      • Directorydinos/
        • [slug].astro
  • astro.config.mjs
  • package.json

通过 API 获取会返回一个包含以下属性的对象:

¥Fetching via the API returns an object that includes the properties:

  • title.rendered - 包含帖子标题的 HTML 渲染。

  • content.rendered - 包含帖子内容的 HTML 渲染。

  • slug - 包含帖子的标题。(这提供了动态生成的各个恐龙页面的链接。)

/src/pages/index.astro
---
import Layout from "../layouts/Layout.astro";
let res = await fetch("https://norian.studio/wp-json/wp/v2/dinos");
let posts = await res.json();
---
<Layout title="Dinos!">
<section>
<h1>List of Dinosaurs</h1>
{
posts.map((post) => (
<article>
<h2>
<a href={`/dinos/${post.slug}/`} set:html={post.title.rendered} />
</h2>
<Fragment set:html={post.content.rendered} />
</article>
))
}
</section>
</Layout>

使用 WordPress API 生成页面

标题部分 使用 WordPress API 生成页面

¥Using the WordPress API to generate pages

每个恐龙的第 src/pages/dinos/[slug].astro 动态生成页面 页。

¥The page src/pages/dinos/[slug].astro dynamically generates a page for each dinosaur.

/src/pages/dinos/[slug].astro
---
import Layout from '../../layouts/Layout.astro';
const { slug } = Astro.params;
let res = await fetch(`https://norian.studio/wp-json/wp/v2/dinos?slug=${slug}`);
let [post] = await res.json();
// The getStaticPaths() is required for static Astro sites.
// If using SSR, you will not need this function.
export async function getStaticPaths() {
let data = await fetch("https://norian.studio/wp-json/wp/v2/dinos");
let posts = await data.json();
return posts.map((post) => ({
params: { slug: post.slug },
props: { post: post },
}));
}
---
<Layout title={post.title.rendered}>
<article>
<h1 set:html={post.title.rendered} />
<Fragment set:html={post.content.rendered} />
</article>
</Layout>

¥Returning embedded resources

_embed 查询参数指示服务器返回相关(嵌入)资源。

¥The _embed query parameter instructs the server to return related (embedded) resources.

src/pages/dinos/[slug].astro
---
const { slug } = Astro.params;
let res = await fetch(`https://norian.studio/wp-json/wp/v2/dinos?slug=${slug}&_embed`);
let [post] = await res.json();
---

_embedded['wp:featuredmedia']['0'].media_details.sizes.medium.source_url 属性被返回,可用于在每个恐龙页面上显示特性图片。(将 medium 替换为你想要的图片尺寸。)

¥The _embedded['wp:featuredmedia']['0'].media_details.sizes.medium.source_url property is returned, and can be used to display the featured image on each dinosaur page. (Replace medium with your desired image size.)

/src/pages/dinos/[slug].astro
<Layout title={post.title.rendered}>
<article>
<img src={post._embedded['wp:featuredmedia']['0'].media_details.sizes.medium.source_url} />
<h1 set:html={post.title.rendered} />
<Fragment set:html={post.content.rendered} />
</article>
</Layout>

¥Publishing your site

要部署你的网站,请访问我们的 部署指南 并按照你首选托管提供商的说明进行操作。

¥To deploy your site visit our deployment guides and follow the instructions for your preferred hosting provider.

¥Community Resources

¥Production Sites

以下网站在生产中使用 Astro + WordPress:

¥The following sites use Astro + WordPress in production:

¥Themes

更多 CMS 指南

Astro 中文网 - 粤ICP备13048890号