PHPackages                             codesoup/metabox-schema - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. codesoup/metabox-schema

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

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.

v1.2.0(1mo ago)046[1 issues](https://github.com/code-soup/metabox-schema/issues)MITPHPPHP &gt;=8.1

Since Apr 25Pushed 3w agoCompare

[ Source](https://github.com/code-soup/metabox-schema)[ Packagist](https://packagist.org/packages/codesoup/metabox-schema)[ Docs](https://github.com/code-soup/metabox-schema)[ RSS](/packages/codesoup-metabox-schema/feed)WikiDiscussions master Synced today

READMEChangelog (3)Dependencies (10)Versions (10)Used By (0)

CodeSoup Metabox Schema
=======================

[](#codesoup-metabox-schema)

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](assets/screenshot-01.png)](assets/screenshot-01.png)

What This Package Does
----------------------

[](#what-this-package-does)

1. **Render form fields** from a schema definition
2. **Sanitize and validate submitted data** against the same schema

Key Features
------------

[](#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](https://skillshare.runkids.cc/).

Installation
------------

[](#installation)

```
composer require codesoup/metabox-schema
```

Quick Start
-----------

[](#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
--------

[](#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
-------------

[](#core-concepts)

### Schema

[](#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

[](#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
- `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

[](#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 Attributes

[](#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

[](#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

[](#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
-------------

[](#api-reference)

### Renderer

[](#renderer)

```
Renderer::render([
    'schema' => $schema,        // Required
    'form_prefix' => 'my_form', // Required
    'entity' => $object,        // Optional
    'values' => $array,         // Optional
    'template_base' => $path    // Optional
]);
```

### Validator

[](#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)

[](#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
---------

[](#extending)

### Custom Validator

[](#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

[](#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

[](#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
------------

[](#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
------------

[](#requirements)

- PHP 8.1+
- WordPress 5.0+ (for escaping functions, wp\_editor, and media library)

Agent Skills
------------

[](#agent-skills)

This package includes [Agent Skills](https://agentskills.io/) for AI-assisted development, compatible with [Skillshare](https://skillshare.runkids.cc/).

### Available Skills

[](#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

[](#installation-1)

```
# Local installation (recommended)
cd /path/to/metabox-schema
skillshare install ./skills --track
skillshare sync
```

### From GitHub

[](#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
-------

[](#license)

MIT License - See LICENSE file for details.

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance94

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~29 days

Total

5

Last Release

35d ago

Major Versions

0.0.3 → v1.1.02026-04-25

### Community

Maintainers

![](https://www.gravatar.com/avatar/00b8448f7b4a45eae365d2016244dddf72ab4f8556747fa41521f23863b09a65?d=identicon)[bobz-zg](/maintainers/bobz-zg)

---

Top Contributors

[![Bobz-zg](https://avatars.githubusercontent.com/u/420604?v=4)](https://github.com/Bobz-zg "Bobz-zg (37 commits)")

---

Tags

composer-packagewordpresswordpress-adminschemavalidationwordpressrendererformmetabox

### Embed Badge

![Health badge](/badges/codesoup-metabox-schema/health.svg)

```
[![Health](https://phpackages.com/badges/codesoup-metabox-schema/health.svg)](https://phpackages.com/packages/codesoup-metabox-schema)
```

###  Alternatives

[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.4M50](/packages/proengsoft-laravel-jsvalidation)[arondeparon/laravel-request-sanitizer

An easy to use request sanitizer that allows you to sanitize your form data before validating it.

112160.9k4](/packages/arondeparon-laravel-request-sanitizer)[evaisse/php-json-schema-generator

A JSON Schema Generator.

20316.0k1](/packages/evaisse-php-json-schema-generator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
