# MetaForge Engine — Modern WordPress Custom Field Builder & Advanced Custom Fields Engine

[![GPLv2 Licensed](https://img.shields.io/badge/License-GPLv2-blue.svg)](https://www.gnu.org/licenses/gpl-2.0.html)
[![WordPress Compatibility](https://img.shields.io/badge/WordPress-6.0+-21759b.svg)](https://wordpress.org)
[![PHP Version](https://img.shields.io/badge/PHP-7.4%20to%208.3-777bb4.svg)](https://php.net)
[![Zero Lock-In](https://img.shields.io/badge/Architecture-Zero%20Lock--In-success.svg)](#zero-lock-in--data-ownership)

**MetaForge Engine** is a high-performance **WordPress custom field builder**, dynamic layout engine, and modern **Advanced Custom Fields engine** built for WordPress developers, agency engineers, and technical teams.

It delivers a visual field builder with 20 core free field types, nested groups, custom post type management, and an enterprise multi-provider AI core—engineered to eliminate database bloat, avoid N+1 query loops, and guarantee complete data ownership with **Zero Lock-In**. Advanced matrix fields (Repeaters, Flexible Content, Gallery, Relationship) are available via the companion plugin **[MetaForge Pro](https://github.com/BoobathiSNS/metaforge-pro)**.

---

## Table of Contents

- [Core Capabilities](#core-capabilities)
  - [WordPress Custom Field Builder (20 Core Free Fields)](#wordpress-custom-field-builder-20-core-free-fields)
  - [WordPress Repeater Fields (MetaForge Pro)](#wordpress-repeater-fields-metaforge-pro)
  - [WordPress Nested Fields & Multi-Dimensional Hierarchies](#wordpress-nested-fields--multi-dimensional-hierarchies)
  - [WordPress Flexible Content & Modular Layout Builder (MetaForge Pro)](#wordpress-flexible-content--modular-layout-builder-metaforge-pro)
  - [High-Performance Advanced Custom Fields Architecture](#high-performance-advanced-custom-fields-architecture)
  - [WordPress Custom Meta Fields & Dynamic Fields](#wordpress-custom-meta-fields--dynamic-fields)
  - [Gutenberg Block Bridge](#gutenberg-block-bridge)
  - [Multi-Provider AI Core](#multi-provider-ai-core)
- [Developer PHP Template API](#developer-php-template-api)
  - [Basic Field Retrieval](#basic-field-retrieval)
  - [Repeater Field Loops](#repeater-field-loops)
  - [Nested Repeater Hierarchy](#nested-repeater-hierarchy)
  - [Flexible Content Layout Dispatching](#flexible-content-layout-dispatching)
  - [Global Options & Taxonomy Meta](#global-options--taxonomy-meta)
  - [Programmatic Local Field Group Registration](#programmatic-local-field-group-registration)
- [Comparison: MetaForge Engine vs Advanced Custom Fields](#comparison-metaforge-engine-vs-advanced-custom-fields)
- [Zero Lock-In & Data Ownership](#zero-lock-in--data-ownership)
- [WP-CLI & CI/CD Integration](#wp-cli--cicd-integration)
- [REST API Endpoints](#rest-api-endpoints)
- [Supported Field Types](#supported-field-types)
- [License & Contributions](#license--contributions)

---

## Core Capabilities

### WordPress Custom Field Builder (20 Core Free Fields)

MetaForge Engine provides an intuitive drag-and-drop visual builder to construct custom field groups across:
* **Custom Post Types & Core Posts/Pages**
* **Categories, Tags & Custom Taxonomy Terms** (`wp_termmeta`)
* **User Profile & Account Screens** (`wp_usermeta`)
* **Global Options Pages** (`metaforge_options`)

All field settings support custom default values, placeholder text, character limits, prepends/appends, and granular location rules.

### WordPress Repeater Fields (Available in MetaForge Pro)

> *Note: Repeater fields and nested sub-repeaters are unlocked with the **[MetaForge Pro](https://github.com/BoobathiSNS/metaforge-pro)** companion plugin.*

Traditional WordPress field builders save each subfield as a separate database row, causing hundreds of queries per page. MetaForge Engine stores repeater data as optimized, normalized structures with single-transient cache lookup:
* Unlimited subfield types (text, images, relational pickers, date pickers)
* Instantaneous drag-and-drop row reordering
* Memory-efficient batch fetching via `metaforge_get_repeater()`
* Zero N+1 query loops on high-traffic queries

### WordPress Nested Fields & Multi-Dimensional Hierarchies

Structure multidimensional data models with nested groups (Free) and sub-repeaters (Pro):
* Nest repeaters inside repeaters (e.g. Schedule &rarr; Days &rarr; Sessions &rarr; Speakers)
* Automatic depth tracking without recursion memory spikes
* Standardized loop semantics using `metaforge_have_rows()` and `metaforge_the_row()`

### WordPress Flexible Content & Modular Layout Builder (Available in MetaForge Pro)

> *Note: Flexible Content layout components are powered by the **[MetaForge Pro](https://github.com/BoobathiSNS/metaforge-pro)** companion plugin.*

Empower content teams to build bespoke landing pages using developer-defined modular blocks:
* Define modular row layouts (Hero Banner, 3-Column Features, Testimonial Slider, CTA)
* Reorder, duplicate, and toggle layouts on the fly
* Developers maintain 100% control over clean, semantic HTML markup via `get_template_part()` dispatchers

### High-Performance Advanced Custom Fields Architecture

Designed as a modern drop-in replacement for Advanced Custom Fields:
* **1-Click Migration**: Scan your database for existing field groups and postmeta under **MetaForge &rarr; Tools &rarr; Switch to MetaForge** and convert them to native MetaForge schemas in seconds.
* **Familiar Developer Workflows**: Syntax parallels classic workflows with native `metaforge_*` equivalents (`metaforge_get_field()`, `metaforge_have_rows()`, and `metaforge_the_row()`).
* **Zero Query Overhead**: Single-read database lookups avoid legacy multi-key postmeta fragmentation.

### WordPress Custom Meta Fields & Dynamic Fields

* Dynamic relational post type selectors with AJAX term filtering
* Live term and user selectors with capability filtering
* Visual Drag-and-Drop Reordering Engine for custom post types and taxonomy terms (`metaforge_post_order`, `metaforge_term_order`)

### Gutenberg Block Bridge

Transform any field group into a native WordPress block (`metaforge/` block namespace) without writing JavaScript or compiling React:
* Automatically maps field configurations to block attributes
* Supports theme template overrides via `template-parts/blocks/{slug}.php` and `blocks/{slug}.php`
* Full live preview in the Gutenberg block editor

### Multi-Provider AI Core

Generate field groups, data schemas, and realistic mock fallback data using your provider of choice:
* **Supported LLMs**: OpenAI (ChatGPT & Responses API), Anthropic Claude, Google Gemini, Groq (Llama), DeepSeek, and OpenRouter
* **Local Security**: API keys are securely encrypted with AES-256-CBC using WordPress `AUTH_KEY` or loaded directly via `MetaForge_AI_API_KEY` in `wp-config.php`
* **Zero Telemetry**: All conversational history is stored exclusively in your local database (`wp_metaforge_ai_memory`)

---

## Developer PHP Template API

MetaForge Engine helper functions are defensively wrapped with `function_exists()`, guaranteeing zero template crashes if the plugin is ever deactivated.

### Basic Field Retrieval

```php
<?php
// Retrieve a field value from the current post
$company_name = metaforge_get_field('company_name');

// Retrieve a field value from a specific post ID
$featured_title = metaforge_get_field('featured_title', 42);

// Direct echo helper
metaforge_the_field('tagline');

// Image field returns a formatted array
$hero_image = metaforge_get_field('hero_image');
if ($hero_image) : ?>
    <img 
        src="<?php echo esc_url($hero_image['url']); ?>" 
        alt="<?php echo esc_attr($hero_image['alt']); ?>" 
        width="<?php echo esc_attr($hero_image['width']); ?>" 
        height="<?php echo esc_attr($hero_image['height']); ?>" 
    />
<?php endif; ?>
```

### Repeater Field Loops *(Requires MetaForge Pro)*

> *Note: Loop helper functions (`metaforge_have_rows()`, `metaforge_the_row()`, `metaforge_get_sub_field()`) are built into MetaForge Engine for zero lock-in theme compatibility, while the Repeater field UI and builder are unlocked via **[MetaForge Pro](https://github.com/BoobathiSNS/metaforge-pro)**.*

```php
<?php
// Loop through a repeater using standard row syntax
if (metaforge_have_rows('team_members')) : ?>
    <div class="team-grid">
        <?php while (metaforge_have_rows('team_members')) : metaforge_the_row(); ?>
            <div class="team-card">
                <?php $photo = metaforge_get_sub_field('member_photo'); ?>
                <?php if ($photo) : ?>
                    <img src="<?php echo esc_url($photo['url']); ?>" alt="<?php echo esc_attr($photo['alt']); ?>">
                <?php endif; ?>
                <h3><?php echo esc_html(metaforge_get_sub_field('member_name')); ?></h3>
                <p class="role"><?php echo esc_html(metaforge_get_sub_field('member_role')); ?></p>
            </div>
        <?php endwhile; ?>
    </div>
    <?php metaforge_reset_rows(); ?>
<?php endif; ?>
```

### Nested Repeater Hierarchy *(Requires MetaForge Pro)*

```php
<?php
// Multi-level nested repeater (Days -> Sessions -> Speakers)
if (metaforge_have_rows('event_days')) : ?>
    <div class="event-schedule">
        <?php while (metaforge_have_rows('event_days')) : metaforge_the_row(); ?>
            <h2><?php echo esc_html(metaforge_get_sub_field('day_title')); ?></h2>

            <?php if (metaforge_have_rows('sessions')) : ?>
                <div class="sessions-list">
                    <?php while (metaforge_have_rows('sessions')) : metaforge_the_row(); ?>
                        <div class="session-item">
                            <h3><?php echo esc_html(metaforge_get_sub_field('session_title')); ?></h3>
                            <span class="time"><?php echo esc_html(metaforge_get_sub_field('session_time')); ?></span>

                            <?php if (metaforge_have_rows('speakers')) : ?>
                                <ul class="speakers">
                                    <?php while (metaforge_have_rows('speakers')) : metaforge_the_row(); ?>
                                        <li><?php echo esc_html(metaforge_get_sub_field('speaker_name')); ?></li>
                                    <?php endwhile; ?>
                                </ul>
                            <?php endif; ?>
                        </div>
                    <?php endwhile; ?>
                </div>
            <?php endif; ?>
        <?php endwhile; ?>
    </div>
    <?php metaforge_reset_rows(); ?>
<?php endif; ?>
```

### Flexible Content Layout Dispatching *(Requires MetaForge Pro)*

```php
<?php
// Flexible content modular layout builder
if (metaforge_have_rows('page_builder')) :
    while (metaforge_have_rows('page_builder')) : metaforge_the_row();
        $layout = metaforge_get_row_layout();
        // Dispatches to template-parts/blocks/{layout_slug}.php
        get_template_part('template-parts/blocks/' . sanitize_file_name($layout));
    endwhile;
    metaforge_reset_rows();
endif;
?>
```

### Global Options & Taxonomy Meta

```php
<?php
// Retrieve a value from a global Options Page
$support_phone = metaforge_get_option('support_phone_number');
// Or using the post_id identifier:
$support_email = metaforge_get_field('support_email', 'options');

// Retrieve a custom field from a Taxonomy Term
$term_id = get_queried_object_id();
$category_color = metaforge_get_field('accent_color', 'term_' . $term_id);

// Retrieve a custom field from a User Profile
$user_id = get_current_user_id();
$github_profile = metaforge_get_field('github_username', 'user_' . $user_id);
```

### Programmatic Local Field Group Registration

```php
<?php
// Register field groups directly in PHP (version control friendly)
add_action('init', function () {
    if (function_exists('metaforge_add_local_field_group')) {
        metaforge_add_local_field_group([
            'key'      => 'group_real_estate_listing',
            'title'    => 'Real Estate Listing Fields',
            'location' => [
                [
                    ['param' => 'post_type', 'operator' => '==', 'value' => 'property']
                ]
            ],
            'fields'   => [
                [
                    'key'   => 'field_prop_price',
                    'label' => 'Price ($)',
                    'name'  => 'property_price',
                    'type'  => 'number',
                ],
                [
                    'key'   => 'field_prop_bedrooms',
                    'label' => 'Bedrooms',
                    'name'  => 'property_bedrooms',
                    'type'  => 'select',
                    'choices' => [
                        '1' => '1 Bedroom',
                        '2' => '2 Bedrooms',
                        '3' => '3+ Bedrooms',
                    ],
                ],
                [
                    'key'   => 'field_prop_gallery',
                    'label' => 'Photo Gallery',
                    'name'  => 'property_gallery',
                    'type'  => 'gallery',
                ]
            ]
        ]);
    }
});
```

---

## Comparison: MetaForge Engine vs Advanced Custom Fields

| Feature | MetaForge Engine | Advanced Custom Fields |
| :--- | :--- | :--- |
| **Core Database Architecture** | Normalized, non-polluting storage with single-read query resolution | Multi-row key/reference fragmentation per field (`wp_postmeta`) |
| **Repeater Performance** | Single-transient cached array; 0 N+1 query loops | Individual row metadata lookup; up to 100+ SQL queries on large lists |
| **Nested Fields Depth** | Unlimited nested repeaters & groups | Limited by query count and server recursion timeouts |
| **Modular Flexible Content** | Native row layouts with template part dispatching | Proprietary format requiring expensive paid add-ons |
| **Gutenberg Block Bridge** | Automatic PHP block generation (`template-parts/blocks/`) | Requires manual `register_block_type` boilerplate |
| **Custom Post Type Manager** | Visual CPT builder with custom icons and rewrite rules | Requires separate CPT plugin or manual PHP code |
| **Custom Taxonomy Manager** | Visual taxonomy builder with post type associations | Requires separate plugin or manual PHP code |
| **Visual Drag-and-Drop Ordering** | Batch ordering for custom posts and terms | Not available natively |
| **Multi-Provider AI Core** | OpenAI, Claude, Gemini, Groq, DeepSeek, OpenRouter | None |
| **Zero Lock-In Guarantee** | Safe `function_exists()` wrappers; pure core meta tables | Templates throw fatal PHP errors if plugin deactivated |
| **1-Click Migration** | Native automated scanner and converter | Manual export/import |

> *Note: Repeaters and Flexible Content layouts are unlocked when paired with **[MetaForge Pro](https://github.com/BoobathiSNS/metaforge-pro)**. Core database normalization, nested group containers, CPT/Taxonomy managers, Gutenberg Block Bridge, and AI Core are 100% free built-in features.*

---

## Zero Lock-In & Data Ownership

Your content belongs to you. MetaForge Engine strictly follows open WordPress core data standards:

1. **Standard Database Tables**: All field values are stored in `wp_postmeta`, `wp_termmeta`, `wp_usermeta`, and `wp_options`.
2. **Accessible Native APIs**: You can always read your raw data via native WordPress functions:
   ```php
   $raw_value = get_post_meta($post_id, 'field_name', true);
   ```
3. **Defensive Deactivation Safety**: All public helper functions (`metaforge_get_field()`, `metaforge_the_field()`, `metaforge_have_rows()`, etc.) are defensively declared with `if (!function_exists(...))`. If MetaForge Engine is ever disabled, your front-end templates continue running without fatal PHP errors.
4. **Git JSON Sync**: Automatically sync all field groups to `.json` files in your theme or plugin repository for seamless version control.

---

## WP-CLI & CI/CD Integration

MetaForge Engine includes native WP-CLI commands for automated deployment and continuous integration pipelines:

```bash
# Synchronize field groups from local JSON definitions into the database
wp metaforge sync

# Export field group configurations to local JSON
wp metaforge export
```

---

## REST API Endpoints

MetaForge Engine registers custom endpoints under the `metaforge/v1` namespace:

| Endpoint | Method | Description |
| :--- | :--- | :--- |
| `/wp-json/metaforge/v1/fields/{post_id}` | `GET` | Retrieve formatted field values for a specific post. |
| `/wp-json/metaforge/v1/fields/{post_id}` | `POST` | Update field values for a specific post (capability protected). |
| `/wp-json/metaforge/v1/schema` | `GET` | Inspect registered field groups and schema definitions. |

---

## Supported Field Types

### 20 Core Free Field Types
* **Basic**: Text, Textarea, Number, Range / Slider, Checkbox, Radio, True/False, Link, Button / CTA.
* **Content & Media**: Image, File, WYSIWYG Editor.
* **Relational**: Post Type Selector, Taxonomy Selector, User Selector.
* **Layout & Structure**: Group (Nested subfield containers), Tab.
* **Advanced**: Color Picker, Date & Time Picker.

### 8 Advanced Fields in MetaForge Pro
* **Matrix & Relational**: Repeater, Flexible Content, Gallery, Relationship.
* **Embed & Utilities**: oEmbed, Icon Picker, Code Editor, Accordion.

---

## License & Contributions

MetaForge Engine is open-source software licensed under the [GNU General Public License v2 or later (GPLv2+)](https://www.gnu.org/licenses/gpl-2.0.html).

Developed by **SearchNScore Solutions Pvt Ltd**.
