diff --git a/assets/css/admin.css b/assets/css/admin.css
index 4233cce..f9b450b 100644
--- a/assets/css/admin.css
+++ b/assets/css/admin.css
@@ -445,3 +445,50 @@
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
+
+
+/* Field group location rules */
+.wem-cf-location-options {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 16px;
+ margin: 12px 0 16px;
+}
+.wem-cf-location-options label {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+.wem-cf-location-pages {
+ max-width: 640px;
+}
+.wem-cf-location-pages select {
+ width: 100%;
+ min-height: 140px;
+}
+.wem-cf-location-pages[hidden] {
+ display: none !important;
+}
+
+
+/* Clear visual feedback for page-only location mode */
+.wem-cf-post-types label.is-disabled {
+ opacity: .55;
+ cursor: not-allowed;
+}
+.wem-cf-post-types label.is-disabled input {
+ cursor: not-allowed;
+}
+.wem-cf-location-options {
+ gap: 12px 22px;
+}
+.wem-cf-location-options label {
+ padding: 2px 0;
+}
+.wem-cf-location-pages {
+ margin-top: 14px;
+ padding: 14px;
+ background: #f6f7f7;
+ border: 1px solid #dcdcde;
+ border-radius: 4px;
+}
diff --git a/assets/js/admin.js b/assets/js/admin.js
index 5a8f627..20e161f 100644
--- a/assets/js/admin.js
+++ b/assets/js/admin.js
@@ -273,9 +273,65 @@
});
}
+ var locationRadios = qsa('input[name="group[location][mode]"]');
+ var locationPages = qs('.wem-cf-location-pages');
+ var postTypeInputs = qsa('input[name="group[post_types][]"]');
+ var previousPostTypeState = null;
+
+ function syncLocation() {
+ var selected = qs('input[name="group[location][mode]"]:checked');
+ var restricted = selected && selected.value === 'specific_pages';
+
+ if (locationPages) {
+ locationPages.hidden = !restricted;
+ var pageSelect = qs('#wem-cf-location-page-ids', locationPages);
+ if (pageSelect) { pageSelect.required = !!restricted; }
+ }
+
+ if (restricted) {
+ if (previousPostTypeState === null) {
+ previousPostTypeState = postTypeInputs.map(function (input) {
+ return { input: input, checked: input.checked };
+ });
+ }
+ postTypeInputs.forEach(function (input) {
+ var isPage = input.value === 'page';
+ input.checked = isPage;
+ input.disabled = !isPage;
+ var label = input.closest('label');
+ if (label) { label.classList.toggle('is-disabled', !isPage); }
+ });
+ } else {
+ postTypeInputs.forEach(function (input) {
+ input.disabled = false;
+ var label = input.closest('label');
+ if (label) { label.classList.remove('is-disabled'); }
+ });
+ if (previousPostTypeState !== null) {
+ previousPostTypeState.forEach(function (item) {
+ item.input.checked = item.checked;
+ });
+ previousPostTypeState = null;
+ }
+ }
+ }
+
+ locationRadios.forEach(function (radio) {
+ radio.addEventListener('change', syncLocation);
+ });
+ syncLocation();
+
var groupForm = qs('#wem-cf-group-form');
if (groupForm && fields) {
groupForm.addEventListener('submit', function (event) {
+ var selectedLocation = qs('input[name="group[location][mode]"]:checked');
+ var pageSelect = qs('#wem-cf-location-page-ids');
+ if (selectedLocation && selectedLocation.value === 'specific_pages' && pageSelect && !Array.from(pageSelect.selectedOptions).length) {
+ event.preventDefault();
+ window.alert('请选择至少一个指定页面。');
+ pageSelect.focus();
+ return;
+ }
if (!qs('.wem-cf-field-card', fields)) {
event.preventDefault();
window.alert('请至少添加一个字段后再保存字段组。');
diff --git a/docs/field-group-location-rules.md b/docs/field-group-location-rules.md
new file mode 100644
index 0000000..c0da2cc
--- /dev/null
+++ b/docs/field-group-location-rules.md
@@ -0,0 +1,126 @@
+# 字段组显示条件(Location Rules)设计说明
+
+## 1. 背景与目标
+
+WEM Content Fields v1.0.0 当前通过字段组的 `post_types[]` 关联内容类型。该机制适合产品、文章等通用字段,但无法让字段组只显示在某一个 Page 的编辑界面。
+
+本功能为字段组增加轻量级显示条件,首个使用场景是只在 About Us 页面显示企业介绍字段组。它不负责前台模板渲染,也不允许客户改变主题布局。
+
+## 2. 范围
+
+### 本次包含
+
+- 字段组可选择「全部关联内容类型」或「仅在指定页面显示」。
+- 指定页面支持选择一个或多个 WordPress Page。
+- 新建与编辑字段组使用同一套配置和校验逻辑。
+- Meta Box 显示、编辑资源加载和常规字段保存使用一致的页面匹配结果。
+- JSON 导入/导出支持显示条件,并对旧版 Schema 做兼容迁移。
+- 未匹配页面不会显示字段组,且不会通过常规 Meta Box 保存流程写入该组字段。
+- 隐藏或修改显示条件不删除既有 Post Meta 数据。
+
+### 本次不包含
+
+- AND/OR 条件构建器。
+- 按用户角色、模板、分类或字段值进行条件组合。
+- Repeater / Gallery 等新字段类型。
+- 前端页面构建器或模板修改。
+- 自动创建页面或自动迁移页面内容。
+
+## 3. 后台界面
+
+扩展现有「新建字段组」和「编辑字段组」页面,不创建新的独立管理页面。
+
+在「应用到内容类型」之后增加「显示条件」区域:
+
+1. **全部关联内容类型**:默认值,保持 v1.0.0 既有行为。
+2. **仅在指定页面显示**:显示 WordPress Page 多选器;至少选择一个页面后才可保存。
+
+该页面选择器只列出可编辑的 Page,保存时由服务端重新验证页面 ID 与页面类型。页面标题只用于显示,不作为唯一身份标识。
+
+## 4. 数据结构
+
+字段组新增可选的 `location` 属性:
+
+```json
+{
+ "location": {
+ "mode": "all"
+ }
+}
+```
+
+指定页面的运行时配置:
+
+```json
+{
+ "location": {
+ "mode": "specific_pages",
+ "page_ids": [123, 456]
+ }
+}
+```
+
+约定:
+
+- 缺少 `location` 的旧字段组按 `mode: all` 处理。
+- `mode` 仅允许 `all` 或 `specific_pages`。
+- `specific_pages` 必须包含至少一个有效的 Page 标识。
+- 页面 ID 在当前站点内作为准确匹配依据,不通过标题猜测目标页面。
+- 显示条件只控制后台字段组的适用对象,不删除字段定义或字段值。
+
+## 5. JSON 导入/导出与 Schema 兼容
+
+由于旧版本插件会忽略未知字段,若继续把新增规则写入 Schema v1,旧版插件可能将受限字段组错误地导入为全局字段组。因此,新导出格式应升级为 Schema v2。
+
+- 导出时,将本地页面 ID 转换为可迁移的页面引用信息(优先使用完整页面路径,并附带 slug/title 供预览和诊断);不把源站 ID 当作目标站 ID 使用。
+- 导入 Schema v1:自动补充 `location.mode = all`,保持旧文件行为。
+- 导入 Schema v2:通过页面路径在目标站点解析 Page ID。
+- 无法唯一解析的页面引用必须在预览中明确警告,不能静默扩大为「全部页面」。
+- 导入后的未解析引用不得匹配其他页面;用户可在字段组编辑界面重新选择目标页面后保存。
+- 导入仍遵循现有策略:不覆盖已有字段组;出现结构或标识冲突时整次导入失败。
+
+具体 JSON 字段命名应在实现时与现有 Importer/Exporter 保持一致,并通过往返测试确认。
+
+## 6. 匹配与保存行为
+
+建议在 Definitions 中增加按当前对象筛选字段组的方法,例如 `for_object( $post_type, $post_id )`,统一处理:
+
+- `add_meta_boxes`:只注册匹配当前对象的字段组。
+- Meta Box 相关资源加载:仅根据匹配字段组判断是否需要媒体库或编辑器资源。
+- `save_post`:仅保存当前对象匹配的字段组,并继续执行现有 Nonce、Capability、Autosave、Revision 和字段白名单校验。
+- REST Meta:由于 `register_post_meta()` 是按 Post Type 注册,页面级规则不能只依靠隐藏 Meta Box 来实现。实现时需为受限字段增加按 `post_id` 判断的授权回调,确保受限字段不会因 REST 写入而绕过页面范围;不受限字段保持现有行为。
+
+如果同一字段组通过 Runtime Definitions 注入,也必须经过同样的规范化与匹配规则;运行时定义不应被写回 Stored Definitions。
+
+## 7. 验收清单
+
+- [ ] 旧字段组缺少 location 时仍按原行为显示。
+- [ ] 新建字段组可以选择「全部关联内容类型」。
+- [ ] 新建字段组可以选择一个或多个指定 Page。
+- [ ] 编辑字段组时正确回显并保存显示规则。
+- [ ] About Us 显示指定字段组,Contact 和 OEM/ODM 不显示。
+- [ ] 未匹配页面不能通过常规 Meta Box 流程保存该组字段。
+- [ ] 页面级字段的 REST 写入遵循相同的页面范围限制。
+- [ ] 改变显示规则或隐藏字段组不会删除旧字段值。
+- [ ] Schema v1 JSON 可以导入,并默认使用全局规则。
+- [ ] Schema v2 导出/导入能保留页面规则。
+- [ ] 导入目标页面不存在或无法唯一匹配时,显示明确警告,且不会退化为全局显示。
+- [ ] 现有字段类型、排序、权限、JSON 冲突检查和数据持久性回归测试通过。
+- [ ] README、Schema 说明和版本信息同步更新。
+
+## 8. 建议实施顺序
+
+1. 完成数据模型与 Schema 迁移设计。
+2. 实现 Normalizer / Validator 与页面匹配方法。
+3. 扩展新建、编辑字段组界面及保存逻辑。
+4. 调整 Meta Box、资源加载、常规保存和 REST 授权。
+5. 更新 JSON 导入/导出及预览警告。
+6. 执行测试、更新 README 并进行 Final Review。
+
+## 9. 设计原则
+
+- 默认兼容,不改变现有字段组行为。
+- 页面级条件属于字段组配置,不属于主题代码。
+- 显示规则、字段定义和实际字段值彼此分离。
+- 页面匹配失败时采取安全失败策略:不显示、不写入、不自动扩大范围。
+- 页面布局仍由经典主题模板控制。
diff --git a/includes/class-definitions.php b/includes/class-definitions.php
index 0d2cc59..eceee5b 100644
--- a/includes/class-definitions.php
+++ b/includes/class-definitions.php
@@ -49,6 +49,26 @@ public function for_post_type( string $post_type ): array {
return $matched;
}
+ public function for_object( string $post_type, int $post_id ): array {
+ $matched = [];
+ foreach ( $this->for_post_type( $post_type ) as $key => $group ) {
+ $location = isset( $group['location'] ) && is_array( $group['location'] ) ? $group['location'] : [];
+ $mode = (string) ( $location['mode'] ?? 'all' );
+ if ( 'all' === $mode ) {
+ $matched[ $key ] = $group;
+ continue;
+ }
+ if ( 'specific_pages' !== $mode ) {
+ continue;
+ }
+ $page_ids = array_map( 'absint', (array) ( $location['page_ids'] ?? [] ) );
+ if ( 'page' === $post_type && $post_id > 0 && in_array( $post_id, $page_ids, true ) ) {
+ $matched[ $key ] = $group;
+ }
+ }
+ return $matched;
+ }
+
public function clear_cache(): void {
$this->cache = null;
}
diff --git a/includes/class-normalizer.php b/includes/class-normalizer.php
index 1a9c6cc..ef43758 100644
--- a/includes/class-normalizer.php
+++ b/includes/class-normalizer.php
@@ -33,11 +33,24 @@ static function ( $value ): bool {
)
);
+ $location_key_exists = array_key_exists( 'location', $input );
+ $has_location = $location_key_exists && is_array( $input['location'] );
+ $location = $has_location ? $input['location'] : [];
+ $location_mode = ! $location_key_exists ? 'all' : ( $has_location ? $this->scalar_string( $location['mode'] ?? '' ) : 'invalid' );
+ if ( ! in_array( $location_mode, [ 'all', 'specific_pages' ], true ) ) {
+ $location_mode = 'invalid';
+ }
+ $page_ids = array_values( array_unique( array_filter( array_map( 'absint', (array) ( $location['page_ids'] ?? [] ) ) ) ) );
+
return [
'key' => trim( $this->scalar_string( $input['key'] ?? '' ) ),
'title' => trim( $this->scalar_string( $input['title'] ?? '' ) ),
'description' => $this->scalar_string( $input['description'] ?? '' ),
'post_types' => array_values( array_unique( $post_types ) ),
+ 'location' => [
+ 'mode' => $location_mode,
+ 'page_ids' => $page_ids,
+ ],
'fields' => $fields,
];
}
diff --git a/includes/class-registry.php b/includes/class-registry.php
index 6ce186c..623500e 100644
--- a/includes/class-registry.php
+++ b/includes/class-registry.php
@@ -40,13 +40,13 @@ public function register(): void {
}
foreach ( $fields as $field ) {
- $this->register_field( $post_type, $field );
+ $this->register_field( $post_type, $field, isset( $group['location'] ) && is_array( $group['location'] ) ? $group['location'] : [] );
}
}
}
}
- private function register_field( string $post_type, array $field ): void {
+ private function register_field( string $post_type, array $field, array $location = [] ): void {
$type = $this->types->get( (string) ( $field['type'] ?? '' ) );
if ( ! $type || empty( $field['meta_key'] ) ) {
return;
@@ -54,9 +54,19 @@ private function register_field( string $post_type, array $field ): void {
$args = $type->get_meta_args( $field );
$args['description'] = (string) ( $field['description'] ?? '' );
- $args['auth_callback'] = static function ( $allowed, $meta_key, $post_id ): bool {
+ $args['auth_callback'] = static function ( $allowed, $meta_key, $post_id ) use ( $location, $post_type ): bool {
$capability = (string) apply_filters( 'wem_cf_manage_capability', 'manage_options' );
- return current_user_can( $capability ) && current_user_can( 'edit_post', (int) $post_id );
+ if ( ! current_user_can( $capability ) || ! current_user_can( 'edit_post', (int) $post_id ) ) {
+ return false;
+ }
+ $mode = (string) ( $location['mode'] ?? 'all' );
+ if ( 'all' === $mode ) {
+ return true;
+ }
+ if ( 'specific_pages' !== $mode ) {
+ return false;
+ }
+ return 'page' === $post_type && in_array( (int) $post_id, array_map( 'absint', (array) ( $location['page_ids'] ?? [] ) ), true );
};
$args = (array) apply_filters( 'wem_cf_meta_args', $args, $field, $post_type );
diff --git a/includes/class-validator.php b/includes/class-validator.php
index cc89abf..62c2274 100644
--- a/includes/class-validator.php
+++ b/includes/class-validator.php
@@ -55,6 +55,27 @@ public function validate_group( array $input, array $existing_groups = [], ?stri
$errors->add( 'post_type_required', '请至少选择一个内容类型。' );
}
+ $raw_location = isset( $input['location'] ) && is_array( $input['location'] ) ? $input['location'] : [];
+ $location_mode = sanitize_key( $raw_location['mode'] ?? 'all' );
+ if ( ! in_array( $location_mode, [ 'all', 'specific_pages' ], true ) ) {
+ $errors->add( 'location_mode_invalid', '显示条件不正确,请重新选择。' );
+ $location_mode = 'all';
+ }
+ $page_ids = array_values( array_unique( array_filter( array_map( 'absint', (array) ( $raw_location['page_ids'] ?? [] ) ) ) ) );
+ if ( 'specific_pages' === $location_mode && ( [ 'page' ] !== $post_types ) ) {
+ $errors->add( 'location_post_type_required', '使用“仅在指定页面显示”时,应用到内容类型必须只选择 Pages。' );
+ }
+ if ( 'specific_pages' === $location_mode && empty( $page_ids ) ) {
+ $errors->add( 'location_pages_required', '请选择至少一个指定页面。' );
+ }
+ if ( 'specific_pages' === $location_mode ) {
+ foreach ( $page_ids as $page_id ) {
+ if ( 'page' !== get_post_type( $page_id ) ) {
+ $errors->add( 'location_page_invalid', '指定页面中包含无效的页面,请刷新后重新选择。' );
+ }
+ }
+ }
+
$other_field_keys = [];
$other_meta_keys = [];
foreach ( $existing_groups as $group_key => $group ) {
@@ -126,6 +147,10 @@ public function validate_group( array $input, array $existing_groups = [], ?stri
'title' => $title,
'description' => sanitize_textarea_field( $input['description'] ?? '' ),
'post_types' => $post_types,
+ 'location' => [
+ 'mode' => $location_mode,
+ 'page_ids' => 'specific_pages' === $location_mode ? $page_ids : [],
+ ],
'fields' => $fields,
];
}
diff --git a/includes/transfer/class-exporter.php b/includes/transfer/class-exporter.php
index 7dcdd01..39e4f03 100644
--- a/includes/transfer/class-exporter.php
+++ b/includes/transfer/class-exporter.php
@@ -15,7 +15,7 @@ public function __construct( Storage $storage ) {
}
/**
- * Build a portable Schema v1 export package from stored definitions only.
+ * Build a portable Schema v2 export package from stored definitions only.
* Runtime definitions injected by filters are intentionally excluded.
*/
public function package( array $selected_keys = [] ): array {
@@ -27,7 +27,7 @@ public function package( array $selected_keys = [] ): array {
if ( '' === $key || ! isset( $stored[ $key ] ) || ! is_array( $stored[ $key ] ) ) {
continue;
}
- $groups[ $key ] = $stored[ $key ];
+ $groups[ $key ] = $this->portable_group( $stored[ $key ] );
}
return [
@@ -39,6 +39,33 @@ public function package( array $selected_keys = [] ): array {
];
}
+ /**
+ * Replace site-local Page IDs with path references for portable JSON.
+ */
+ private function portable_group( array $group ): array {
+ $location = ! array_key_exists( 'location', $group ) ? [ 'mode' => 'all' ] : ( is_array( $group['location'] ) ? $group['location'] : [ 'mode' => 'invalid' ] );
+ if ( 'specific_pages' === ( $location['mode'] ?? 'all' ) ) {
+ $refs = [];
+ foreach ( array_map( 'absint', (array) ( $location['page_ids'] ?? [] ) ) as $page_id ) {
+ $page = get_post( $page_id );
+ if ( ! $page || 'page' !== $page->post_type ) {
+ continue;
+ }
+ $refs[] = [
+ 'path' => trim( (string) get_page_uri( $page_id ), '/' ),
+ 'slug' => (string) $page->post_name,
+ 'title' => (string) $page->post_title,
+ ];
+ }
+ $group['location'] = [ 'mode' => 'specific_pages', 'page_refs' => $refs ];
+ } elseif ( 'all' === ( $location['mode'] ?? 'all' ) ) {
+ $group['location'] = [ 'mode' => 'all' ];
+ } else {
+ $group['location'] = [ 'mode' => 'invalid' ];
+ }
+ return $group;
+ }
+
public function json( array $selected_keys = [] ) {
$package = $this->package( $selected_keys );
diff --git a/includes/transfer/class-importer.php b/includes/transfer/class-importer.php
index 5b5fded..df9d716 100644
--- a/includes/transfer/class-importer.php
+++ b/includes/transfer/class-importer.php
@@ -36,7 +36,7 @@ public function inspect_json( string $json ) {
}
$schema_version = isset( $data['schema_version'] ) ? absint( $data['schema_version'] ) : 0;
- if ( WEM_CF_SCHEMA_VERSION !== $schema_version ) {
+ if ( ! in_array( $schema_version, [ 1, WEM_CF_SCHEMA_VERSION ], true ) ) {
return new \WP_Error(
'unsupported_schema',
sprintf( '当前插件支持 Schema v%d,该文件为 Schema v%d。', WEM_CF_SCHEMA_VERSION, $schema_version )
@@ -48,6 +48,42 @@ public function inspect_json( string $json ) {
return new \WP_Error( 'no_groups', '导入文件中没有字段组。' );
}
+
+ if ( 2 === $schema_version ) {
+ foreach ( $raw_groups as $group_key => &$raw_group ) {
+ if ( ! is_array( $raw_group ) ) {
+ continue;
+ }
+ if ( array_key_exists( 'location', $raw_group ) && ! is_array( $raw_group['location'] ) ) {
+ return new \WP_Error( 'invalid_location_shape', sprintf( '字段组 %s 的显示条件格式无效,未执行导入。', sanitize_key( (string) $group_key ) ) );
+ }
+ $location = isset( $raw_group['location'] ) ? $raw_group['location'] : [ 'mode' => 'all' ];
+ if ( ! in_array( (string) ( $location['mode'] ?? 'all' ), [ 'all', 'specific_pages' ], true ) ) {
+ return new \WP_Error( 'invalid_location_mode', sprintf( '字段组 %s 的显示条件无效,未执行导入。', sanitize_key( (string) $group_key ) ) );
+ }
+ if ( 'all' === ( $location['mode'] ?? 'all' ) ) {
+ $raw_group['location'] = [ 'mode' => 'all' ];
+ continue;
+ }
+ $page_ids = [];
+ foreach ( (array) ( $location['page_refs'] ?? [] ) as $page_ref ) {
+ if ( ! is_array( $page_ref ) || '' === trim( (string) ( $page_ref['path'] ?? '' ) ) ) {
+ return new \WP_Error( 'invalid_page_reference', sprintf( '字段组 %s 包含无效的页面引用,未执行导入。', sanitize_key( (string) $group_key ) ) );
+ }
+ $page = get_page_by_path( trim( (string) $page_ref['path'], '/' ), OBJECT, 'page' );
+ if ( ! $page || 'page' !== $page->post_type ) {
+ return new \WP_Error( 'page_reference_not_found', sprintf( '字段组 %s 引用的页面“%s”在目标站点不存在。请先创建该页面,或在目标站点手动创建字段组。', sanitize_key( (string) $group_key ), sanitize_text_field( (string) ( $page_ref['title'] ?? $page_ref['path'] ) ) ) );
+ }
+ $page_ids[] = (int) $page->ID;
+ }
+ if ( empty( $page_ids ) ) {
+ return new \WP_Error( 'page_reference_empty', sprintf( '字段组 %s 没有可匹配的指定页面,未执行导入。', sanitize_key( (string) $group_key ) ) );
+ }
+ $raw_group['location'] = [ 'mode' => 'specific_pages', 'page_ids' => array_values( array_unique( $page_ids ) ) ];
+ }
+ unset( $raw_group );
+ }
+
$groups = $this->normalizer->groups( $raw_groups );
if ( empty( $groups ) ) {
return new \WP_Error( 'no_valid_groups', '导入文件中没有可识别的字段组。' );
diff --git a/wem-content-fields.php b/wem-content-fields.php
index 1f7d479..b0205b6 100644
--- a/wem-content-fields.php
+++ b/wem-content-fields.php
@@ -2,7 +2,7 @@
/**
* Plugin Name: WEM Content Fields
* Description: 一个轻量、可迁移的 WordPress 结构化字段管理插件,基于原生 Post Meta API。
- * Version: 1.0.0
+ * Version: 1.1.0
* Author: WEM
* Text Domain: wem-content-fields
* Requires at least: 6.4
@@ -14,8 +14,8 @@
exit;
}
-define( 'WEM_CF_VERSION', '1.0.0' );
-define( 'WEM_CF_SCHEMA_VERSION', 1 );
+define( 'WEM_CF_VERSION', '1.1.0' );
+define( 'WEM_CF_SCHEMA_VERSION', 2 );
define( 'WEM_CF_FILE', __FILE__ );
define( 'WEM_CF_PATH', plugin_dir_path( __FILE__ ) );
define( 'WEM_CF_URL', plugin_dir_url( __FILE__ ) );