跳转到正文

构建文档站点

文档最好与其描述的代码放在一起。撰写者喜欢 Markdown,审阅者希望在拉取请求中查看更改,而发布时文档也应与代码处于同一次提交中。另一方面,WordPress 需要将文章存入数据库:搜索、固定链接、修订版本和编辑器都在这里。

Blockstudio 页面集合将二者连接起来。一个包含 Markdown 文件的文件夹会变成一组真正的 WordPress 文章,拥有专属文章类型、URL 基础路径,以及父子层级结构。layout.php 文件会用基于同一数据构建的导航包装集合中的每个页面。文件仍是事实来源,而明确执行的同步命令会将其写入数据库。

本指南将逐步为一个名为 acme 的主题构建一个小型文档部分:包含清单、Markdown 页面、用于生成更新日志的加载器、同步操作,以及带侧边栏和上一篇、下一篇链接的布局。

你将构建的内容

代码
theme/
└── pages/
    └── docs/
        ├── pages.json
        ├── layout.php
        ├── loader.php
        ├── index.md
        ├── getting-started.md
        ├── data/
        │   └── releases.json
        └── guide/
            ├── index.md
            ├── install.md
            └── configure.md

同步后,此集合会提供以下 URL:

来源 公共 URL
index.md /docs/
getting-started.md /docs/getting-started/
guide/index.md /docs/guide/
guide/install.md /docs/guide/install/
guide/configure.md /docs/guide/configure/
加载器条目 /docs/changelog/

步骤 1:集合清单

集合是 pages/ 内包含 pages.json 清单的文件夹。创建 pages/docs/pages.json:

JSON
{
  "collection": "docs",
  "title": "Documentation",
  "postType": "acme_docs",
  "postTypeArgs": {
    "label": "Docs"
  },
  "defaults": {
    "postStatus": "publish",
    "templateLock": "contentOnly"
  }
}

collection 是集合别名,并成为公开的 URL 基础路径。postType 会将集合中的每个页面存入专属文章类型,因此文档不会与管理后台中的普通页面混在一起。如果该文章类型尚不存在,Blockstudio 会注册它。注册默认值为公开、分层,在 REST API 中可用,支持标题、编辑器、页面属性、缩略图、摘要和修订版本,重写别名则与集合别名相同。postTypeArgs 会合并到这些默认值上,因此此清单只更改管理标签。

defaults 会将页面属性应用于集合中的每个页面。这里的每个页面都会在同步时发布,并锁定为仅可编辑内容,因此编辑者可以在编辑器中修正错字,但无法重新排列由 Markdown 定义的结构。

步骤 2:在 Markdown 中编写页面

在集合中,每个 Markdown 文件都是一个页面。文件位置决定其身份,因此 frontmatter 是可选的。你可以用它设置标题、排序顺序,以及之后要读取的任何额外数据。

Markdown
---
title: Introduction
order: 0
description: What Acme does and where to start.
---

# Introduction

Acme is a toolkit for building fast WordPress sites.
Start with [Getting Started](/docs/getting-started/).
Markdown
---
title: Getting Started
order: 10
---

# Getting Started

Install the theme, then activate it under **Appearance > Themes**.

```bash
wp theme activate acme
```

指南部分是一个拥有专属 index.md 的文件夹,它会成为其同级页面的父页面:

Markdown
---
title: Guide
order: 20
---

# Guide

Task-focused walkthroughs for everyday work.
Markdown
---
title: Installation
order: 10
---

# Installation

| Requirement | Version |
| --- | --- |
| WordPress | 6.7+ |
| PHP | 8.2+ |
Markdown
---
title: Configuration
order: 20
---

# Configuration

Settings live in `acme.json` at the theme root.

> Changes apply on the next deploy.

Blockstudio 会从每个文件推导出逻辑路径和页面名称:

文件 路径 页面名称
index.md . docs-home
getting-started.md getting-started docs-getting-started
guide/index.md guide docs-guide
guide/install.md guide/install docs-guide-install

guide/install.md 和 guide/install/index.md 会生成相同的路径,因此之后可以在平铺文件和文件夹之间切换,而不更改 URL。

order 用于排列同级页面,并会写入文章的菜单顺序。没有指定顺序的页面排在有顺序的页面之后,然后按标题排序。Blockstudio 无法识别的 frontmatter 键(例如上面的 description)会保留在页面的 meta 数组中。

同步期间,Markdown 会被解析为 GitHub 风格的 Markdown,转换为 HTML,然后解析为原生区块。存储的文章包含区块,而不是 Markdown 文本。标题会获得稳定的锚点,表格会变为 core/table,引用块会变为 core/quote,围栏代码会变为保留语言类名的 core/preformatted 区块。以下是本安装页面存储的内容(已去除首尾空白):

HTML
<!-- wp:heading {"level":1,"anchor":"installation"} --><h1 id="installation" class="wp-block-heading">Installation</h1><!-- /wp:heading -->
<!-- wp:table --><figure class="wp-block-table"><table>
<thead><tr><th>Requirement</th><th>Version</th></tr></thead>
...
</table></figure><!-- /wp:table -->

步骤 3:使用加载器生成页面

有些页面更适合自动生成,而不是手动编写。更新日志就是一个很好的例子:发布数据已经存在,手动将其复制到 Markdown 中容易造成内容不一致。集合可以包含一个返回额外页面定义的 loader.php。

将发布数据保存在集合中:

JSON
[
  { "version": "1.1.0", "date": "2026-09-01", "notes": "Added dark mode." },
  { "version": "1.0.0", "date": "2026-06-15", "notes": "First release." }
]

然后从中构建一个 Markdown 页面:

PHP
<?php
$releases = json_decode(
	(string) file_get_contents( __DIR__ . '/data/releases.json' ),
	true
);

$markdown = "# Changelog\n";

foreach ( $releases as $release ) {
	$markdown .= "\n## {$release['version']}\n\n";
	$markdown .= "Released {$release['date']}. {$release['notes']}\n";
}

return array(
	'pages' => array(
		array(
			'name'        => 'docs-changelog',
			'title'       => 'Changelog',
			'path'        => 'changelog',
			'order'       => 90,
			'content'     => $markdown,
			'contentType' => 'markdown',
		),
	),
);

加载器只会在明确执行发现和同步时运行,不会在普通页面浏览时运行。应确保其行为确定且仅依赖本地内容:读取主题中的文件没有问题,但不能获取远程 API,否则同步会依赖该服务是否可访问。

加载器页面会标记为生成页面。如果某个条目从加载器输出中消失,下次同步时其文章会被视为孤立项,并由 blockstudio/pages/orphan_action 过滤器处理;默认情况下,该过滤器会将其移至回收站。

加载器还可以返回 paths,将其他本地文件夹中的 Markdown 挂载到集合中,也可以选择使用前缀。集合根目录之外的文件夹需要使用 blockstudio/pages/allow_external_loader_path 过滤器。完整格式请参阅集合加载器。

步骤 4:同步

只有在你明确要求时,内容才会写入数据库:

命令行
wp bs pages sync

该命令会发现所有页面源文件,注册 acme_docs 文章类型,创建或更新文章,并输出摘要行,其中包含 discovered、created、updated、unchanged、removed 和 failed 的数量。如果在没有更改的情况下再次运行,所有页面都会报告为未更改,也不会写入文章。部署脚本需要完整报告时,请添加 --format=json。

同步后,文章结构会与文件树一致。guide/install 是 guide 的子级, 而后者是集合根节点的子级。每篇文章的菜单顺序取自前置元数据中的 order。 集合 URL 由集合别名和每个页面的逻辑路径组合而成:

代码
/docs/
/docs/getting-started/
/docs/guide/
/docs/guide/install/
/docs/guide/configure/
/docs/changelog/

无需重新保存固定链接。注册的集合文章类型发生变化时,集合重写规则会自动刷新。

将同步纳入部署流程。前端和管理后台请求都不会运行页面发现,因此只复制新的 Markdown 文件、却未运行 wp bs pages sync 的部署,会继续提供旧内容。

步骤 5:布局

现在文章已经存在,但每篇文章仍会使用主题的普通单篇模板进行渲染,而且没有导航。在 pages.json 旁放置一个 layout.php,即可包装集合中每个页面的前端渲染:

PHP
<?php
$current = blockstudio_current_page();
$tree    = blockstudio_page_tree( 'docs' );

// Flatten the tree in reading order for previous and next links.
$flat    = array();
$flatten = function ( array $nodes ) use ( &$flatten, &$flat ) {
	foreach ( $nodes as $node ) {
		$flat[] = $node;
		$flatten( $node['children'] );
	}
};
$flatten( $tree );

$keys     = array_column( $flat, 'key' );
$position = array_search( $current['key'] ?? null, $keys, true );
$previous = false !== $position ? ( $flat[ $position - 1 ] ?? null ) : null;
$next     = false !== $position ? ( $flat[ $position + 1 ] ?? null ) : null;

$render_nav = function ( array $nodes ) use ( &$render_nav, $current ) {
	echo '<ul>';
	foreach ( $nodes as $node ) {
		$is_current = ( $node['key'] ?? null ) === ( $current['key'] ?? null );
		printf(
			'<li><a href="%s"%s>%s</a>',
			esc_url( $node['permalink'] ?? '#' ),
			$is_current ? ' aria-current="page"' : '',
			esc_html( $node['title'] )
		);
		if ( array() !== $node['children'] ) {
			$render_nav( $node['children'] );
		}
		echo '</li>';
	}
	echo '</ul>';
};
?>
<div class="docs">
	<nav class="docs-sidebar" aria-label="Documentation">
		<?php $render_nav( $tree ); ?>
	</nav>

	<article class="docs-content">
		<?php echo blockstudio_page_content(); ?>

		<nav class="docs-pager" aria-label="Previous and next">
			<?php if ( $previous ) : ?>
				<a rel="prev" href="<?php echo esc_url( $previous['permalink'] ?? '#' ); ?>">
					<?php echo esc_html( $previous['title'] ); ?>
				</a>
			<?php endif; ?>
			<?php if ( $next ) : ?>
				<a rel="next" href="<?php echo esc_url( $next['permalink'] ?? '#' ); ?>">
					<?php echo esc_html( $next['title'] ); ?>
				</a>
			<?php endif; ?>
		</nav>
	</article>
</div>

blockstudio_page_tree('docs') 会返回集合的嵌套节点,并按 order 和标题排序;每个节点的子节点位于 children 中。这里的根节点是介绍页面,其他页面都在其下方。每个节点都包含 key、title、path 和 permalink。按此顺序展开树形结构即可得到阅读顺序,上一篇和下一篇链接只需要这些信息。

blockstudio_page_content() 会输出 WordPress 将通过 the_content 渲染的页面正文。省略它,内容就会隐藏。在网站位于 https://example.com 的 /docs/guide/install/ 上,布局会渲染以下内容(已修剪):

HTML
<nav class="docs-sidebar" aria-label="Documentation">
  <ul><li><a href="https://example.com/docs/">Introduction</a><ul>
    <li><a href="https://example.com/docs/getting-started/">Getting Started</a></li>
    <li><a href="https://example.com/docs/guide/">Guide</a><ul>
      <li><a href="https://example.com/docs/guide/install/" aria-current="page">Installation</a></li>
      <li><a href="https://example.com/docs/guide/configure/">Configuration</a></li>
    </ul></li>
    <li><a href="https://example.com/docs/changelog/">Changelog</a></li>
  </ul></li></ul>
</nav>
...
<a rel="prev" href="https://example.com/docs/guide/">Guide</a>
<a rel="next" href="https://example.com/docs/guide/configure/">Configuration</a>

布局只会在主循环中的单篇前端请求上运行。它不会更改已存储的 post_content,也不会包装编辑器画布。其路径存储在每篇同步后的文章中,并属于页面指纹的一部分,因此编辑布局后会在下次同步时生效。

在 PHP 中读取集合数据

布局辅助函数是对 Blockstudio\Pages 类的轻量封装。在模板、区块或插件中,两种形式都可以使用:

辅助函数 类方法 返回值
blockstudio_pages('docs') Pages::pages('docs') 集合中所有页面的平铺列表,以页面键为键排序
blockstudio_page_tree('docs') Pages::tree('docs') 带有 children 的嵌套节点
blockstudio_page_children('docs-guide', 'docs') Pages::children('docs-guide', 'docs') 单个页面的直接子级
blockstudio_page_collection('docs') Pages::collection('docs') 清单中的集合数据
blockstudio_current_page() Pages::current_page() 正在渲染的页面,或 null
Pages::get_page('docs-guide-install') 按名称获取单个页面

页面数组包含已同步的 post_id、permalink、name、key、title、 path、order、collection、postType,以及 meta 数组。Frontmatter 附加内容会存入 meta,因此布局可以输出简介的摘要:

PHP
<?php $summary = $current['meta']['description'] ?? ''; ?>

在前端请求中,这些函数会读取已同步的文章和上次同步时存储的配置。它们从不读取 Markdown 文件,因此不会产生文件系统开销。前端仅提供已发布的页面。

Tools 的原始 Markdown

由于页面来自 Markdown 文件,Blockstudio 也可以提供原始源文件。为页面请求带有 .md 后缀的版本,例如 /docs/guide/install.md,或者向常规的 URL 发送 Accept: text/markdown。响应会省略 frontmatter,并通过规范的 Link 标头指回 HTML 页面。这对搜索索引器、助手和其他读取纯文本的工具很有用。由内联加载器内容生成的页面没有源文件,因此不会有 .md 响应。

使用一个筛选器将其关闭:

PHP
add_filter( 'blockstudio/pages/serve_markdown', '__return_false' );

提示

让路径承载结构。 移动文件后,其路径、父级和 URL 会在下次同步时随之更新。仅当 URL 与文件位置不同时,才使用 frontmatter path。

页面需要更多内容时,将 page.json 与 Markdown 配合使用。 同时包含 page.json 和 index.md 的文件夹会使用 JSON 存放页面属性,例如 postId 或 templateLock,并使用 Markdown 存放内容。index.md 中的 Frontmatter 优先于匹配的 page.json 值。

在文件中编写内容,而不是在编辑器中。 使用 templateLock: "contentOnly" 时,编辑者可以直接修正文案,但下次同步更改过的源文件时,存储的内容会被文件内容覆盖。请将 Markdown 视为编写文档的位置。应该归编辑者管理的页面,则应在 page.json 中添加 "sync": false;常规同步会跳过它,而 Blockstudio\Pages::force_sync() 只会创建一次。

更改文章类型是安全的。 如果集合从 page 改为自定义文章类型,只要已同步文章的存储身份匹配,就会原地迁移,因此文章 ID 会保留。

后续步骤