codesoup/metabox-schema 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

codesoup/metabox-schema

最新稳定版本:v1.1.0

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.

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

  • 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
  • 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 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'
    ]
];

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

  • 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

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:

  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.

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_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 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.

统计信息

  • 总下载量: 11
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 8
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-02-01

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固