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.
Requires
- php: >=8.1
Requires (Dev)
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-master
- v1.2.1
- v1.2.0
- v1.1.0
- dev-release/1.3.0
- dev-cursor/fix-number-field-validation-22db
- dev-cursor/fix-entity-method-resolution-22db
- dev-cursor/wp-plugin-production-deploy-e7c4
- dev-cursor/skills-proposals-e7c4
- dev-cursor/skills-audit-e7c4
- dev-cursor/skills-audit-fixes-e7c4
- dev-cursor/release-1-3-0-review-fixes-e7c4
- dev-cursor/release-1-3-0-to-master-e7c4
- dev-cursor/testing-automation-proposal-e7c4
- dev-v/1.2.1
- dev-v/1.3.0
- dev-v/1.2.0
- dev-v/1.1.0
This package is auto-updated.
Last update: 2026-11-25 05:34:02 UTC
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 (theme or plugin dependency):
composer require codesoup/metabox-schema
WordPress plugin: copy this repository into wp-content/plugins/metabox-schema, run composer install --no-dev, and activate Metabox Schema. See readme.txt for WordPress.org-style metadata (Requires at least, Tested up to, etc.).
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', 'help_position' => 'after', 'wrapper_class' => 'field-wrapper', 'required_class' => 'mandatory' ] ];
Supported Field Types
Input Fields:
text,email,url,number,date,password,tel,color,range
Content Fields:
textarea- Multi-line text inputselect- Dropdown with optionsradio- Single selection from inline optionscheckbox- Single yes/no or agreement checkboxcheckbox_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 Wrapper
Auto-generated IDs:
- Field ID:
form-prefix-field-name - Wrapper ID:
form-prefix-field-name-wrap
Wrapper Classes:
- Custom classes via
wrapper_class(string or array) - Auto-adds
has-requiredclass whenvalidation.required = true - Configurable via
required_classoption
Use attributes array for field-level 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.
Filters
The package provides field-level filters for customizing behavior:
Filter Required Class
add_filter('codesoup_metabox_field_required_class', function($class, $field_name, $config) { // Override required class for specific fields if ($field_name === 'critical_field') { return 'mandatory-field'; } return $class; }, 10, 3);
Filter Help Position
add_filter('codesoup_metabox_field_help_position', function($position, $field_name, $config) { // Show help before all textarea fields if ($config['type'] === 'textarea') { return 'before'; } return $position; }, 10, 3);
Filter Sanitization
add_filter('codesoup_metabox_schema_sanitize_default', function($filtered, $value, $type) { // Custom sanitization for custom field types if ($type === 'my_custom_type') { return sanitize_text_field($value); } return $filtered; }, 10, 3);
API Reference
Renderer
Renderer::render([ 'schema' => $schema, // Required 'form_prefix' => 'my_form', // Required 'entity' => $object, // Optional 'values' => $array, // Optional 'template_base' => $path, // Optional 'default_required_class' => 'is-required', // Optional (default: 'has-required') 'default_help_position' => 'before' // Optional (default: 'after') ]);
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 6.0+ (for escaping functions,
wp_editor, and media library)
Release versions are kept in sync across metabox-schema.php, readme.txt, and composer.json — see docs/release-version-sync.md.
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.
