Search by

codesoup / metabox-schema

bobz-zg

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.

Package info

github.com/code-soup/metabox-schema

pkg:composer/codesoup/metabox-schema

Statistics

Installs: 47

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 6


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.

Metabox Schema Screenshot

What This Package Does

  1. Render form fields from a schema definition
  2. 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 validation
  • custom-templates.php - Override default field templates
  • extend-validator.php - Add custom validation rules
  • extend-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 input
  • select - Dropdown with options
  • radio - Single selection from inline options
  • checkbox - Single yes/no or agreement checkbox
  • checkbox_group - Multiple checkbox options
  • wp_editor - WordPress rich text editor
  • media - WordPress media library picker

Display Fields:

  • html - HTML content display
  • label - Field labels
  • help - Help text

Validation Rules

  • required - Field must have value
  • min / max - Min/max value or length
  • format - 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-required class when validation.required = true
  • Configurable via required_class option

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:

  1. Static 'value' in schema
  2. Callable 'value' => fn() => get_option('key')
  3. Entity methods 'value' => 'get_email' (calls $entity->get_email())
  4. 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_Editor
  • get_options() - Select
  • get_editor_settings() - WP_Editor
  • get_content() - HTML
  • get_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.