codesoup/metabox-schema
Composer 安装命令:
composer require codesoup/metabox-schema
包简介
Schema-driven form builder system for WordPress. Define fields as PHP arrays, use Renderer class to render forms and sanitize POST data. Use Validator to validate user input against your schema.
README 文档
README
Schema-driven form generator system for WordPress developers. Define fields as PHP arrays, use provided classes to render forms, sanitize data and validate user input against defined schema.
What This Package Does
- Render form fields from a schema definition
- Sanitize and validate submitted data against the same schema
Key Features
- 16+ field types included
- Custom field type registration support
- Template override (global, per-type, per-field)
- Extensible validation and rendering
- WordPress media library integration
- Grid layout support
- Agent skills for AI-assisted development, compatible with Skillshare.
Installation
composer require codesoup/metabox-schema
Quick Start
use CodeSoup\MetaboxSchema\Renderer; use CodeSoup\MetaboxSchema\Validator; // 1. Define schema $schema = [ 'email' => [ 'type' => 'email', 'label' => 'Email', 'validation' => [ 'required' => true ] ] ]; // 2. Render fields Renderer::render([ 'schema' => $schema, 'form_prefix' => 'contact' ]); // 3. Validate data $validator = new Validator(); $validated_data = $validator->validate( $_POST['contact'], $schema ); if ( $validator->has_errors() ) { $errors = $validator->get_errors(); }
Examples
See the docs/ directory for complete working examples:
basic-usage.php- Complete form rendering and validationcustom-templates.php- Override default field templatesextend-validator.php- Add custom validation rulesextend-renderer.php- Customize rendering behavior
Core Concepts
Schema
Array defining field structure, validation rules, and configuration:
$schema = [ 'field_name' => [ 'type' => 'text', 'label' => 'Field Label', 'value' => 'default', 'validation' => [ 'required' => true, 'min' => 3, 'max' => 50, 'pattern' => '^[a-zA-Z0-9]+$' ], 'errors' => [ 'required' => 'Please enter a value', 'min' => 'Value is too short' ], 'attributes' => [ 'class' => 'custom-class another-class', 'placeholder' => 'Enter value', 'maxlength' => 50, 'data-custom' => 'value', 'data-validate' => 'true' ], 'help' => 'Help text' ] ];
Supported Field Types
Input Fields:
text,email,url,number,date,password,tel,color,range
Content Fields:
textarea- Multi-line text inputselect- Dropdown with optionscheckbox_group- Multiple checkbox optionswp_editor- WordPress rich text editormedia- WordPress media library picker
Display Fields:
html- HTML content displaylabel- Field labelshelp- Help text
Validation Rules
required- Field must have valuemin/max- Min/max value or lengthformat- Format validation (email, url, date)pattern- Regex pattern
Custom error messages via 'errors' array (see schema example above).
Field IDs and Attributes
Each field automatically gets an ID in format form-prefix-field-name. Use attributes array for CSS classes and data attributes. Note: id and name in attributes are ignored (auto-generated).
Value Resolution
Fields can get values from:
- Static
'value'in schema - Callable
'value' => fn() => get_option('key') - Entity methods
'value' => 'get_email'(calls$entity->get_email()) - Values array passed to Renderer
Custom Templates
Templates are organized in subdirectories by field type:
templates/
├── input/
│ └── template.php
├── textarea/
│ └── template.php
├── select/
│ └── template.php
└── ...
Override templates globally or per-field:
// Global override Renderer::render([ 'schema' => $schema, 'template_base' => __DIR__ . '/templates' ]); // Single field override $schema['bio']['template_path'] = __DIR__ . '/templates/textarea/custom.php';
See docs/custom-templates.php and docs/templates/ for details.
API Reference
Renderer
Renderer::render([ 'schema' => $schema, // Required 'form_prefix' => 'my_form', // Required 'entity' => $object, // Optional 'values' => $array, // Optional 'template_base' => $path // Optional ]);
Validator
$validator = new Validator(); $validated_data = $validator->validate( $data, $schema ); if ( $validator->has_errors() ) { $errors = $validator->get_errors(); // Returns: [ 'email' => 'Email is required', 'age' => 'Age must be at least 18' ] }
Field Methods (Available in Templates)
Common Methods (All Fields):
get_field_id(),get_field_name(),get_type(),get_label()get_value(),get_escaped_value(),get_escaped_textarea_value()is_required(),get_required_attr(),get_attributes_string()get_help(),get_wrapper()
Field-Specific Methods:
get_rows()- Textarea, WP_Editorget_options()- Selectget_editor_settings()- WP_Editorget_content()- HTMLget_button_text(),get_media_type(),get_preview_size()- Media
See docs/templates/ for template usage examples.
Extending
Custom Validator
class Custom_Validator extends Validator { protected function validate_value( $value, $context ) { // Custom validation logic return parent::validate_value( $value, $context ); } }
See docs/extend-validator.php for complete example.
Custom Renderer
class Custom_Renderer extends Renderer { protected function render_field( $field_name, $field_config ) { // Custom rendering logic parent::render_field( $field_name, $field_config ); } }
See docs/extend-renderer.php for complete example.
Custom Field Types
Register custom field types on a Renderer instance to avoid conflicts with other plugins:
use CodeSoup\MetaboxSchema\Abstract_Field; use CodeSoup\MetaboxSchema\Renderer; // Create custom field class class Color_Picker_Field extends Abstract_Field { protected function get_template_name(): string { return 'color-picker'; } public function get_palette(): array { return $this->config['palette'] ?? array(); } } // Register on renderer instance $renderer = new Renderer(); $renderer->register_field_type( 'color_picker', Color_Picker_Field::class ); // Use in schema $renderer->render_fields([ 'schema' => [ 'brand_color' => [ 'type' => 'color_picker', 'label' => 'Brand Color', 'palette' => [ '#FF0000', '#00FF00', '#0000FF' ] ] ], 'form_prefix' => 'settings' ]);
Benefits of instance-based registration:
- ✅ No conflicts between plugins using different implementations
- ✅ Each renderer has isolated field registry
- ✅ Safe for multi-plugin WordPress environments
Architecture
- Renderer - Static
render()method, extensible protected methods - Validator - Instance-based, extensible validation rules
- Field_Factory - Creates field instances from configuration
- Abstract_Field - Base class for all field types
- Field Classes - Input_Field, Textarea_Field, Select_Field, Media_Field, WP_Editor_Field, HTML_Field, Label_Field, Help_Field
- Value_Resolver - Trait for resolving values from multiple sources
- String_Formatter - Utility for string transformations
- Config_Sanitizer - Sanitizes and validates configuration arrays
- Constants - Default values and configuration constants
Requirements
- PHP 8.1+
- WordPress 5.0+ (for escaping functions, wp_editor, and media library)
Agent Skills
This package includes Agent Skills for AI-assisted development, compatible with Skillshare.
Available Skills
- schema-definition - Define field schemas with validation rules
- field-renderer - Render forms from schemas
- template-creator - Create custom field templates
- validator - Validate and sanitize user input
- custom-field-registration - Register custom field types
- utilities - Use utility classes
Installation
# Local installation (recommended) cd /path/to/metabox-schema skillshare install ./skills --track skillshare sync
From GitHub
# SSH skillshare install git@github.com:code-soup/metabox-schema.git/skills # HTTPS with token export GITHUB_TOKEN=your_token_here skillshare install github.com/code-soup/metabox-schema/skills
See skills/README.md for details.
License
MIT License - See LICENSE file for details.
codesoup/metabox-schema 适用场景与选型建议
codesoup/metabox-schema 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 46 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 02 月 01 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「form」 「schema」 「wordpress」 「validation」 「renderer」 「metabox」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 codesoup/metabox-schema 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 codesoup/metabox-schema 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 codesoup/metabox-schema 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Extension for Opis JSON Schema
EAV modeling package for Eloquent and Laravel.
Diese Contao 4 Erweiterung stellt Google reCAPTCHA V2 in Form eines neuen Formularfeldes im Formulargenerator bereit. This extension provides Google reCAPTCHA V2 in the form of a new form field in the form generator of Contao Open Source CMS.
serialize Symfony Forms into JSON schema
Build forms from schema
Specifications like JSON schemas and other things for mosparo
统计信息
- 总下载量: 46
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 41
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-02-01
