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.

08PHP

Since Mar 15Pushed 2mo agoCompare

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

READMEChangelogDependenciesVersions (4)Used By (0)

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

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

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)

- 15+ 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
- PHP 8.0+ with strict typing
- 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
- `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.

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

22

—

LowBetter than 22% of packages

Maintenance58

Moderate activity, may be stable

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity16

Early-stage or recently created project

 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 ~2 days

Total

3

Last Release

101d ago

### 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 (22 commits)")

### 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

[webmozart/assert

Assertions to validate method input/output with nice error messages.

7.6k894.0M1.2k](/packages/webmozart-assert)[bensampo/laravel-enum

Simple, extensible and powerful enumeration implementation for Laravel.

2.0k15.9M104](/packages/bensampo-laravel-enum)[swaggest/json-schema

High definition PHP structures with JSON-schema based validation

48612.5M73](/packages/swaggest-json-schema)[stevebauman/purify

An HTML Purifier / Sanitizer for Laravel

5325.6M19](/packages/stevebauman-purify)[ashallendesign/laravel-config-validator

A package for validating your Laravel app's config.

217905.3k5](/packages/ashallendesign-laravel-config-validator)[crazybooot/base64-validation

Laravel validators for base64 encoded files

1341.9M8](/packages/crazybooot-base64-validation)

PHPackages © 2026

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