字段模式指南
Blockstudio 的字段系统单独来看很简单:向 blockstudio.attributes 添加字段,然后在模板中通过 $a 访问它。但实际区块很少只有一个字段。它们会包含相关设置组、根据其他字段显示或隐藏的字段、行结构复杂的重复器,以及需要在区块编辑器之外查询的数据。
本指南汇集了常见字段模式的实用配方。每个配方都展示 block.json 配置和对应的模板代码。你可以直接复制到自己的区块中,并按需调整。
条件字段
最常见的模式:根据另一个字段的值显示或隐藏字段。这样只呈现相关选项,让编辑器保持简洁。
切换开关以显示选项
在 CTA 区块中,用户启用按钮后才显示其他设置:
{
"name": "my-theme/cta",
"title": "Call to Action",
"blockstudio": {
"attributes": [
{ "id": "heading", "type": "text", "label": "Heading", "default": "Ready to get started?" },
{ "id": "description", "type": "textarea", "label": "Description" },
{ "id": "showButton", "type": "toggle", "label": "Show Button", "default": true },
{
"id": "buttonText",
"type": "text",
"label": "Button Text",
"default": "Get Started",
"conditions": [[{ "id": "showButton", "operator": "==", "value": true }]]
},
{
"id": "buttonUrl",
"type": "link",
"label": "Button Link",
"conditions": [[{ "id": "showButton", "operator": "==", "value": true }]]
}
]
}
}
仅当切换开关开启时,按钮文本和链接字段才会显示。在模板中,渲染前先检查开关状态:
<div useBlockProps>
<h2><?php echo esc_html( $a['heading'] ); ?></h2>
<?php if ( $a['description'] ) : ?>
<p><?php echo esc_html( $a['description'] ); ?></p>
<?php endif; ?>
<?php if ( $a['showButton'] && $a['buttonUrl'] ) : ?>
<a href="<?php echo esc_url( $a['buttonUrl']['url'] ); ?>">
<?php echo esc_html( $a['buttonText'] ); ?>
</a>
<?php endif; ?>
</div>
通过选择切换字段组
Hero 区块根据背景类型决定显示哪些字段:
{
"name": "my-theme/hero",
"title": "Hero",
"blockstudio": {
"attributes": [
{ "id": "heading", "type": "text", "label": "Heading" },
{
"id": "bgType",
"type": "select",
"label": "Background Type",
"default": "color",
"options": [
{ "value": "color", "label": "Solid Color" },
{ "value": "gradient", "label": "Gradient" },
{ "value": "image", "label": "Image" },
{ "value": "video", "label": "Video" }
]
},
{
"id": "bgColor",
"type": "color",
"label": "Background Color",
"conditions": [[{ "id": "bgType", "operator": "==", "value": "color" }]]
},
{
"id": "bgGradient",
"type": "gradient",
"label": "Background Gradient",
"conditions": [[{ "id": "bgType", "operator": "==", "value": "gradient" }]]
},
{
"id": "bgImage",
"type": "files",
"label": "Background Image",
"multiple": false,
"conditions": [[{ "id": "bgType", "operator": "==", "value": "image" }]]
},
{
"id": "bgVideo",
"type": "files",
"label": "Background Video",
"multiple": false,
"allowedTypes": ["video"],
"conditions": [[{ "id": "bgType", "operator": "==", "value": "video" }]]
},
{
"id": "overlay",
"type": "range",
"label": "Overlay Opacity",
"default": 50,
"min": 0,
"max": 100,
"conditions": [[{ "id": "bgType", "operator": "!=", "value": "color" }]]
}
]
}
}
覆盖层不透明度字段使用 !=,因此除纯色外都会显示。一次只会显示一个背景字段。color 字段会返回一个包含颜色的 value、name 和 slug 的数组,因此模板读取 ['value']:
<?php
$bg_style = match ( $a['bgType'] ) {
'color' => $a['bgColor'] ? "background-color: {$a['bgColor']['value']}" : '',
'gradient' => $a['bgGradient'] ? "background: {$a['bgGradient']}" : '',
'image' => $a['bgImage'] ? "background-image: url({$a['bgImage']['url']})" : '',
default => '',
};
?>
<div useBlockProps style="<?php echo esc_attr( $bg_style ); ?>">
<?php if ( $a['bgType'] === 'video' && $a['bgVideo'] ) : ?>
<video autoplay muted loop playsinline>
<source src="<?php echo esc_url( $a['bgVideo']['url'] ); ?>" />
</video>
<?php endif; ?>
<h1><?php echo esc_html( $a['heading'] ); ?></h1>
</div>
OR 条件
当多个条件中的任意一个成立时显示字段。每个内部数组是一组 AND 条件;外部数组则用 OR 组合这些条件组:
{
"id": "caption",
"type": "text",
"label": "Caption",
"conditions": [
[{ "id": "bgType", "operator": "==", "value": "image" }],
[{ "id": "bgType", "operator": "==", "value": "video" }]
]
}
当 bgType 为 “image” 或 “video” 时,这会显示说明文字字段。
链式条件
同一内部数组中的多个条件使用 AND 逻辑:
{
"id": "altText",
"type": "text",
"label": "Alt Text",
"conditions": [[
{ "id": "bgType", "operator": "==", "value": "image" },
{ "id": "bgImage", "operator": "!empty" }
]]
}
仅当 bgType 为 “image” 且已选择图像时,才会显示替代文本字段。
全局条件
根据文章类型、文章 ID 或用户角色显示字段,而不是根据其他字段值显示:
{
"id": "seoTitle",
"type": "text",
"label": "SEO Title",
"conditions": [[{ "type": "postType", "operator": "==", "value": "page" }]]
}
可用的全局条件类型:postType、postId、userRole、userId。
整理有序的设置
随着区块变得复杂,将字段整理到逻辑分组中,可以让检查器保持易于管理。
用分组进行视觉整理
分组会在检查器中创建可折叠的分区。匿名分组(没有 id)只用于视觉整理;其中的字段通过原始 ID 访问:
{
"name": "my-theme/card",
"title": "Card",
"blockstudio": {
"attributes": [
{
"type": "group",
"title": "Content",
"attributes": [
{ "id": "title", "type": "text", "label": "Title" },
{ "id": "description", "type": "textarea", "label": "Description" },
{ "id": "image", "type": "files", "label": "Image", "multiple": false }
]
},
{
"type": "group",
"title": "Link",
"attributes": [
{ "id": "url", "type": "link", "label": "URL" },
{ "id": "openInNewTab", "type": "toggle", "label": "Open in New Tab" }
]
},
{
"type": "group",
"title": "Appearance",
"attributes": [
{
"id": "style",
"type": "select",
"label": "Style",
"default": "elevated",
"options": [
{ "value": "elevated", "label": "Elevated" },
{ "value": "outlined", "label": "Outlined" },
{ "value": "flat", "label": "Flat" }
]
},
{ "id": "accentColor", "type": "color", "label": "Accent Color" }
]
}
]
}
}
<div useBlockProps>
<h3><?php echo esc_html( $a['title'] ); ?></h3>
<p><?php echo esc_html( $a['description'] ); ?></p>
</div>
直接访问字段:$a['title']、$a['style']、$a['accentColor']。分组只会影响检查器的布局。
使用 bs_get_group 的命名分组
分组有 id 时,其子字段 ID 会添加前缀。使用 bs_get_group() 去除此前缀:
{
"id": "author",
"type": "group",
"title": "Author",
"attributes": [
{ "id": "name", "type": "text", "label": "Name" },
{ "id": "role", "type": "text", "label": "Role" },
{ "id": "avatar", "type": "files", "label": "Avatar", "multiple": false }
]
}
不使用辅助函数时,字段的访问方式为 $a['author_name']、$a['author_role']、$a['author_avatar']。使用辅助函数后:
<?php $author = bs_get_group( $a, 'author' ); ?>
<div class="author">
<?php if ( $author['avatar'] ) : ?>
<img src="<?php echo esc_url( $author['avatar']['url'] ); ?>" alt="" />
<?php endif; ?>
<p><?php echo esc_html( $author['name'] ); ?></p>
<p><?php echo esc_html( $author['role'] ); ?></p>
</div>
当多个分组中出现相同字段名(e.g、author_name 和 company_name)时,或者你想将整个分组传递给局部模板时,命名分组很有用。
分组中的网格布局
使用 style 属性,将分组子项并排排列:
{
"type": "group",
"title": "Dimensions",
"style": {
"display": "grid",
"grid-template-columns": "1fr 1fr",
"grid-gap": "16px"
},
"attributes": [
{ "id": "width", "type": "unit", "label": "Width", "default": "100%", "switch": false },
{ "id": "height", "type": "unit", "label": "Height", "default": "auto", "switch": false }
]
}
两个单位字段会在检查器中并排显示,而不是上下堆叠。这种布局适用于尺寸组合、边距/内边距值,或任何概念上成对的字段。
用选项卡划分主要分区
区块设置较多时,选项卡比一长串分组更清晰:
{
"type": "tabs",
"tabs": [
{
"title": "Content",
"attributes": [
{ "id": "title", "type": "text", "label": "Title" },
{ "id": "body", "type": "wysiwyg", "label": "Body" }
]
},
{
"title": "Media",
"attributes": [
{ "id": "image", "type": "files", "label": "Image", "multiple": false },
{ "id": "video", "type": "files", "label": "Video", "multiple": false, "allowedTypes": ["video"] }
]
},
{
"title": "Settings",
"attributes": [
{ "id": "layout", "type": "select", "label": "Layout", "options": [
{ "value": "left", "label": "Media Left" },
{ "value": "right", "label": "Media Right" }
]},
{ "id": "fullWidth", "type": "toggle", "label": "Full Width" }
]
}
]
}
每个选项卡中的字段都可以像顶层字段一样访问:$a['title']、$a['image']、$a['layout']。选项卡只是一个 UI 容器。
重复器模式
重复器允许用户添加多行字段,是列表、网格、时间线以及任何项目数量可变的组件不可或缺的功能。
带约束的基本重复器
包含 1 到 6 个项目的功能列表:
{
"id": "features",
"type": "repeater",
"label": "Features",
"min": 1,
"max": 6,
"textButton": "Add Feature",
"attributes": [
{ "id": "icon", "type": "icon", "label": "Icon" },
{ "id": "title", "type": "text", "label": "Title", "default": "Feature" },
{ "id": "description", "type": "textarea", "label": "Description" }
]
}
<div useBlockProps class="grid grid-cols-3 gap-8">
<?php foreach ( $a['features'] as $feature ) : ?>
<div>
<?php if ( $feature['icon'] ) : ?>
<?php bs_render_icon( $feature['icon'] ); ?>
<?php endif; ?>
<h3><?php echo esc_html( $feature['title'] ); ?></h3>
<p><?php echo esc_html( $feature['description'] ); ?></p>
</div>
<?php endforeach; ?>
</div>
自定义行标签
默认情况下,折叠的重复器行会显示通用标签。使用 textMinimized 改为显示字段值:
{
"id": "team",
"type": "repeater",
"label": "Team Members",
"textMinimized": { "id": "name", "fallback": "Team Member" },
"attributes": [
{ "id": "name", "type": "text", "label": "Name" },
{ "id": "role", "type": "text", "label": "Role" },
{ "id": "photo", "type": "files", "label": "Photo", "multiple": false }
]
}
折叠一行时,会显示人员姓名,而不是“第 1 行”。姓名字段为空时会使用 fallback。你还可以添加 prefix 和 suffix 字符串。
重复器内的条件字段
重复器中的字段可以使用原始 id(无需前缀)引用同一行中的其他字段:
{
"id": "links",
"type": "repeater",
"label": "Links",
"attributes": [
{ "id": "label", "type": "text", "label": "Label" },
{ "id": "url", "type": "link", "label": "URL" },
{
"id": "isExternal",
"type": "toggle",
"label": "External Link"
},
{
"id": "externalNote",
"type": "message",
"label": "Note",
"description": "External links open in a new tab with rel=\"noopener\".",
"conditions": [[{ "id": "isExternal", "operator": "==", "value": true }]]
}
]
}
在重复器中引用外部字段
如果重复器内的条件需要检查重复器外的字段,请添加 "context": "main":
{
"id": "showDescriptions",
"type": "toggle",
"label": "Show Descriptions",
"default": true
},
{
"id": "items",
"type": "repeater",
"label": "Items",
"attributes": [
{ "id": "title", "type": "text", "label": "Title" },
{
"id": "description",
"type": "textarea",
"label": "Description",
"conditions": [[{
"id": "showDescriptions",
"operator": "==",
"value": true,
"context": "main"
}]]
}
]
}
如果没有 "context": "main",条件会在重复器行中查找 showDescriptions 字段。添加后,条件便会检查根级切换开关。
重复器中的选项卡
重复器中不支持选项卡:在重复器行内使用 tabs 字段时,编辑器会显示提示,而不会显示字段;PHPStan 扩展也会报告此问题。请改为将一行中的字段平铺排列。对于较长的行,自定义行标签(textMinimized)能让折叠行更易阅读;此外,行内条件可以隐藏只有部分行需要的字段,如上面的示例所示。
在重复器上设置 "minimized": true,即可让现有行默认折叠。新添加的行会立即展开。展开状态的例外会保存在此浏览器中,并在编辑器重新加载后保留;这属于编辑偏好,不会保存为文章内容。未设置 minimized 的重复器仍会沿用现有行为,默认展开。
媒体模式
带备用值的单张图像
{
"id": "image",
"type": "files",
"label": "Image",
"multiple": false
}
<?php if ( $a['image'] ) : ?>
<img
src="<?php echo esc_url( $a['image']['url'] ); ?>"
alt="<?php echo esc_attr( $a['image']['alt'] ); ?>"
<?php if ( isset( $a['image']['sizes']['full-width'], $a['image']['sizes']['full-height'] ) ) : ?>
width="<?php echo esc_attr( $a['image']['sizes']['full-width'] ); ?>"
height="<?php echo esc_attr( $a['image']['sizes']['full-height'] ); ?>"
<?php endif; ?>
/>
<?php endif; ?>
默认的 returnFormat 是 "object",它提供 ID、title、alt、caption、description、href、url 和 sizes。sizes 包含每种已注册图像尺寸(sizes['large'])的 URL 及其尺寸(sizes['large-width']、sizes['large-height'])。完整列表请参阅 渲染属性。
限制数量的图库
{
"id": "gallery",
"type": "files",
"label": "Gallery",
"multiple": true,
"max": 6,
"allowedTypes": ["image"]
}
<?php if ( $a['gallery'] ) : ?>
<div class="grid grid-cols-3 gap-4">
<?php foreach ( $a['gallery'] as $image ) : ?>
<img
src="<?php echo esc_url( $image['url'] ); ?>"
alt="<?php echo esc_attr( $image['alt'] ); ?>" />
<?php endforeach; ?>
</div>
<?php endif; ?>
可通过开关禁用的图像
switch 属性会添加一个眼睛图标,让用户无需删除字段值即可禁用字段:
{
"id": "logo",
"type": "files",
"label": "Logo",
"multiple": false,
"switch": true
}
<?php
$is_disabled = ! empty( $a['_disabled'] ) && in_array( 'logo', $a['_disabled'], true );
if ( $a['logo'] && ! $is_disabled ) : ?>
<img src="<?php echo esc_url( $a['logo']['url'] ); ?>" alt="" />
<?php endif; ?>
用户可以关闭徽标,而不删除已上传的文件。重新启用后,同一文件会再次显示。
返回格式选项
控制文件字段的返回内容:
// Full object (default)
{ "id": "photo", "type": "files", "returnFormat": "object", "multiple": false }
// $a['photo']['url'], $a['photo']['alt'], $a['photo']['sizes']['full-width'], etc.
// Just the ID
{ "id": "photo", "type": "files", "returnFormat": "id", "multiple": false }
// $a['photo'] = 42
// Just the URL
{ "id": "photo", "type": "files", "returnFormat": "url", "multiple": false }
// $a['photo'] = "https://example.com/photo.jpg"
需要自行调用 wp_get_attachment_image() 时使用 "id"。简单背景图像使用 "url"。其他情况使用 "object"(默认值)。
使用 "returnFormat": "id" 时,导入的字符串引用(例如 "buckshair-home")会原样传递。编辑器会显示没有缩略图的备用卡片,重复器行中也一样。打开或保存页面不会将标量引用转换为数组。由附件 ID 和字符串引用组成的混合列表也可以使用;只有正数附件 ID 才会在媒体库中查找。
Blockstudio 不会将自定义字符串引用解析为附件。若要在不同站点间使用可移植名称,请在自己的渲染筛选器或模板中解析。像往常一样,在媒体库中选择替代项会保存其附件 ID。
动态选项
从文章填充
列出所有已发布页面的选择字段:
{
"id": "linkedPage",
"type": "select",
"label": "Linked Page",
"stylisedUi": true,
"populate": {
"type": "query",
"query": "posts",
"arguments": {
"post_type": "page",
"post_status": "publish",
"posts_per_page": -1
}
}
}
该字段会自动使用页面标题作为标签、文章 ID 作为值进行填充。使用填充配置中的 returnFormat 自定义映射:
"populate": {
"type": "query",
"query": "posts",
"arguments": { "post_type": "page" },
"returnFormat": { "value": "ID", "label": "post_title" }
}
从分类法术语填充
{
"id": "category",
"type": "select",
"label": "Category",
"stylisedUi": true,
"populate": {
"type": "query",
"query": "terms",
"arguments": {
"taxonomy": "category",
"hide_empty": true
}
}
}
从 PHP 函数填充
{
"id": "postType",
"type": "select",
"label": "Post Type",
"populate": {
"type": "function",
"function": "get_post_types",
"arguments": { "public": true }
}
}
将静态选项与填充选项结合
将硬编码选项与动态选项结合。使用 position 控制填充选项的显示位置:
{
"id": "source",
"type": "select",
"label": "Source",
"options": [
{ "value": "manual", "label": "Manual Entry" },
{ "value": "latest", "label": "Latest Posts" }
],
"populate": {
"type": "query",
"query": "posts",
"arguments": { "post_type": "page" },
"position": "after"
}
}
静态选项会先显示,之后是动态填充的页面。
存储可查询的数据
默认情况下,字段值存储在 post_content 中的区块属性里,无法通过 WP_Query 查询。需要按字段值筛选或排序文章时,请使用存储功能。
将文章元数据用于可查询字段
{
"id": "featured",
"type": "toggle",
"label": "Featured",
"storage": {
"type": "postMeta",
"postMetaKey": "is_featured"
}
},
{
"id": "priority",
"type": "number",
"label": "Priority",
"default": 0,
"min": 0,
"max": 100,
"storage": {
"type": "postMeta",
"postMetaKey": "priority_score"
}
}
现在可以查询精选文章:
$featured = new WP_Query( array(
'meta_query' => array(
array(
'key' => 'is_featured',
'value' => '1',
),
),
'orderby' => 'meta_value_num',
'meta_key' => 'priority_score',
'order' => 'DESC',
) );
元数据键会通过 show_in_rest 自动注册,因此也可在 REST API 中使用。
双重存储
同时存储在区块属性和文章元数据中。区块属性使模板能通过 $a 获取该值,而文章元数据则让该值可供查询:
{
"id": "eventDate",
"type": "date",
"label": "Event Date",
"storage": {
"type": ["block", "postMeta"],
"postMetaKey": "event_date"
}
}
将选项存储用于全局值
对于需要在整个站点保持一致的设置,请使用选项存储:
{
"id": "companyName",
"type": "text",
"label": "Company Name",
"storage": {
"type": "option",
"optionKey": "site_company_name"
}
}
该值存储在 wp_options 中,可通过 get_option('site_company_name') 在任何位置访问。用户在任意区块实例中编辑此字段时,该值都会全局更新。
可复用字段定义
多个区块共用相同字段结构时,可将其定义为自定义字段,然后在各处引用。
创建自定义字段
在主题的 blockstudio/fields/ 目录中创建一个 field.json:
theme/
└── blockstudio/
└── fields/
└── cta/
└── field.json
{
"name": "cta",
"title": "Call to Action",
"attributes": [
{ "id": "label", "type": "text", "label": "Button Label", "default": "Learn More" },
{ "id": "url", "type": "link", "label": "Button URL" },
{ "id": "style", "type": "select", "label": "Button Style", "default": "primary", "options": [
{ "value": "primary", "label": "Primary" },
{ "value": "secondary", "label": "Secondary" },
{ "value": "outline", "label": "Outline" }
]}
]
}
使用自定义字段
在任意区块中通过 "type": "custom/cta" 引用它:
{
"blockstudio": {
"attributes": [
{ "id": "heading", "type": "text", "label": "Heading" },
{ "type": "custom/cta" }
]
}
}
CTA 字段会内联到区块中。直接访问它们:$a['label']、$a['url']、$a['style']。
使用 idStructure 为自定义字段添加前缀
多次使用同一个自定义字段时,添加 idStructure 为 ID 加上前缀:
{
"blockstudio": {
"attributes": [
{ "type": "custom/cta", "idStructure": "primary_{id}" },
{ "type": "custom/cta", "idStructure": "secondary_{id}" }
]
}
}
第一个 CTA 的字段会变为 primary_label、primary_url、primary_style。第二个则变为 secondary_label 等。
覆盖默认值
引用自定义字段时,可自定义特定字段:
{
"type": "custom/cta",
"idStructure": "hero_{id}",
"overrides": {
"label": { "default": "Get Started", "label": "CTA Label" },
"style": { "default": "primary" }
}
}
覆盖项会与原始定义合并。你可以更改默认值、标签、条件或其他属性。
渲染模式
空值检查
大多数字段类型在为空时会返回 false。渲染前务必先检查:
<?php if ( $a['title'] ) : ?>
<h2><?php echo esc_html( $a['title'] ); ?></h2>
<?php endif; ?>
对于数字,0 是有效值。如果需要区分“空”和“零”,请使用严格比较:
<?php if ( $a['count'] !== 0 || $a['count'] !== false ) : ?>
<span><?php echo esc_html( $a['count'] ); ?></span>
<?php endif; ?>
returnFormat: both 的选择字段
需要同时获取值(用于逻辑判断)和标签(用于显示)时:
{
"id": "status",
"type": "select",
"label": "Status",
"returnFormat": "both",
"options": [
{ "value": "active", "label": "Active" },
{ "value": "paused", "label": "On Hold" },
{ "value": "closed", "label": "Closed" }
]
}
<?php if ( $a['status'] ) : ?>
<span class="badge badge--<?php echo esc_attr( $a['status']['value'] ); ?>">
<?php echo esc_html( $a['status']['label'] ); ?>
</span>
<?php endif; ?>
使用 attributes 字段设置数据属性
attributes 字段类型允许用户添加自定义数据属性:
{
"id": "dataAttrs",
"type": "attributes",
"label": "Data Attributes",
"link": true,
"media": true
}
<div useBlockProps <?php bs_render_data_attributes( $a['dataAttrs'] ); ?>>
Content here.
</div>
根据字段值生成 CSS 变量
根据选定字段生成自定义 CSS 属性:
{
"id": "textColor", "type": "color", "label": "Text Color"
},
{
"id": "fontSize", "type": "unit", "label": "Font Size", "default": "1rem"
}
<div useBlockProps style="<?php bs_render_variables( $a, array( 'textColor', 'fontSize' ) ); ?>">
<p>Styled content.</p>
</div>
这会输出 style="--text-color: #333; --font-size: 1rem;"(字段 ID 会转换为 kebab-case)。在 CSS 中使用这些变量:
p {
color: var(--text-color);
font-size: var(--font-size);
}