### Install and Initialize HyperFields Source: https://context7.com/estebanforge/hyperfields/llms.txt Install the library via Composer and include the autoloader to bootstrap the library. ```php // Install via Composer // composer require estebanforge/hyperfields // In your plugin or theme require_once __DIR__ . '/vendor/autoload.php'; // HyperFields is now ready to use use HyperFields\HyperFields; use HyperFields\Field; use HyperFields\OptionsPage; ``` -------------------------------- ### Add Tab with Fields Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Example of creating tabs for UI organization. This does not affect storage format. ```php $tabs = HyperFields::makeTabs('settings_tabs', 'Settings'); $tabs->addTab('general', 'General', [ HyperFields::makeField('text', 'site_tagline', 'Tagline') ]); ``` -------------------------------- ### Production Composer Install Source: https://github.com/estebanforge/hyperfields/blob/main/AGENTS.md Installs Composer dependencies for a production environment, disabling development packages and optimizing the autoloader. ```bash composer install --no-dev --optimize-autoloader ``` -------------------------------- ### Create a Custom Metabox with HyperFields Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields-examples.md This example demonstrates how to create a simple post metabox using HyperFields. It shows basic field types like text, textarea, and checkbox, and how to target specific post types. Copy this function to your theme or plugin and activate it. ```php function my_custom_metabox() { $container = HyperFields::makePostMeta('my_meta', 'My Fields') ->where('post') ->setContext('normal'); $container->addField( HyperFields::makeField('text', 'my_field', 'My Field') ); } // Activate it add_action('init', 'my_custom_metabox'); ``` -------------------------------- ### Install HyperFields via Composer Source: https://github.com/estebanforge/hyperfields/blob/main/README.md Use this command to add the library to your WordPress project dependencies. ```bash composer require estebanforge/hyperfields ``` -------------------------------- ### Example JSON Export Bundle Shape Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md This is an example of the JSON structure that results from using a custom SchemaConfig, including the injected 'site' data and custom 'type' and 'schema_version'. ```json { "site": { "url": "https://example.com", "environment": "staging" }, "schema_version": 2, "type": "my_plugin_manifest", "generated_at": "...", "modules": { "options": {} }, "errors": [] } ``` -------------------------------- ### Configure and Render Admin Page with Export/Import UI Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Use `ExportImportPageConfig` to define settings for an admin page and `ExportImportUI::renderConfigured` to render it. This approach is suitable for immutable, config-driven setups. ```php use HyperFields\Admin\ExportImportPageConfig; use HyperFields\Admin\ExportImportUI; $config = new ExportImportPageConfig( options: ['my_plugin_options' => 'My Plugin Settings'], optionGroups: ['my_plugin_options' => 'Core'], prefix: 'myp_', ); echo ExportImportUI::renderConfigured($config); ``` -------------------------------- ### Storage Adapter Interface Source: https://github.com/estebanforge/hyperfields/blob/main/docs/wp-settings-compatibility-plan.md Defines the interface for storage strategies, including get, set, delete, and all methods. Used by HyperFields to manage settings data. ```php interface Store { public function get(string $key, mixed $default = null): mixed; public function set(string $key, mixed $value): bool; public function delete(string $key): bool; public function all(): array; } ``` -------------------------------- ### Declare URL Field Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Declare a URL field for link inputs. It defaults to '#' in this example. ```php $field = HyperFields::makeField('url', 'button_url', 'Button URL'); $field->setDefault('#'); ``` -------------------------------- ### Save and Retrieve Map Field Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Save and retrieve a map field for simple key/value storage. This example stores social handles. ```php $field = HyperFields::makeField('map', 'social_handles', 'Social handles'); hf_update_field('social_handles', ['twitter' => '@me', 'github' => 'me'], 'options', [ 'type' => 'map' ]); $handles = hf_get_field('social_handles', 'options', [ 'default' => [] ]); ``` -------------------------------- ### Bootstrap HyperFields within a Class Hook Source: https://github.com/estebanforge/hyperfields/blob/main/docs/library-bootstrap.md When deferring plugin setup to a bootstrap class hooked on `plugins_loaded`, define constants for the main plugin file and URL, then use them to initialize HyperFields. This pattern is useful for organizing plugin initialization. ```php define('MY_PLUGIN_FILE', __FILE__); define('MY_PLUGIN_URL', plugin_dir_url(__FILE__)); add_action('plugins_loaded', function () { $autoload = plugin_dir_path(MY_PLUGIN_FILE) . 'vendor/autoload.php'; if (file_exists($autoload)) { require_once $autoload; } if (class_exists('\HyperFields\LibraryBootstrap')) { \HyperFields\LibraryBootstrap::init([ 'plugin_file' => MY_PLUGIN_FILE, 'plugin_url' => MY_PLUGIN_URL . 'vendor/estebanforge/hyperfields/', ]); } MyPlugin\Plugin::get_instance(); }); ``` -------------------------------- ### Register Options Page with HyperFields Source: https://github.com/estebanforge/hyperfields/blob/main/AGENTS.md Example of how to register a new options page in the WordPress admin area using the HyperFields API. This includes basic page configuration and section definitions. ```php use HyperFields\HyperFields; HyperFields::registerOptionsPage([ 'page_title' => 'My Settings', 'menu_title' => 'Settings', 'capability' => 'manage_options', 'menu_slug' => 'my-settings', 'sections' => [...], ]); ``` -------------------------------- ### Get and Set Field Values Source: https://context7.com/estebanforge/hyperfields/llms.txt Use helper functions to read and write field values across different storage contexts like options, post meta, user meta, and term meta. Supports default values and type-based sanitization during updates. ```php // Get option values $tagline = hf_get_field('site_tagline', 'options', ['default' => '']); $color = hf_get_field('accent_color', 'options', ['default' => '#000000']); // Save option values with type-based sanitization hf_update_field('site_tagline', 'New Tagline', 'options', ['type' => 'text']); hf_update_field('accent_color', '#ff5500', 'options', ['type' => 'color']); // Get post meta by post ID $custom_title = hf_get_field('custom_title', 123, ['default' => '']); $featured = hf_get_field('is_featured', get_the_ID(), ['default' => false]); // Save post meta hf_update_field('custom_title', 'My Custom Title', 123, ['type' => 'text']); // Get/set user meta $bio = hf_get_field('user_bio', 'user_45', ['default' => '']); hf_update_field('onboarding_done', true, 'user_45', ['type' => 'checkbox']); // Get/set term meta $term_color = hf_get_field('category_color', 'term_7', ['default' => '#000']); hf_update_field('category_color', '#ff0000', 'term_7', ['type' => 'color']); // Delete field values hf_delete_field('old_setting', 'options'); hf_delete_field('deprecated_meta', 123); ``` -------------------------------- ### Initialize UI components Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Use factory methods to create objects for building admin pages, sections, tabs, and fields. ```php $opts = HyperFields::makeOptionPage('Site Settings', 'site-settings'); $field = HyperFields::makeField('text', 'site_tagline', 'Tagline'); $tabs = HyperFields::makeTabs('settings_tabs', 'Settings'); $rep = HyperFields::makeRepeater('social', 'Social Links'); $sec = HyperFields::makeSection('general', 'General'); ``` -------------------------------- ### Arguments for LibraryBootstrap::init() Source: https://github.com/estebanforge/hyperfields/blob/main/docs/library-bootstrap.md Explicit arguments are required for vendored usage to ensure correct URL resolution, especially in complex directory structures or symlinked environments. ```APIDOC ## GET /api/users/{userId} ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /api/users/{userId} ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user to retrieve. #### Query Parameters - **include_details** (boolean) - Optional - Whether to include detailed user information. ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. - **details** (object) - Optional - Additional user details. #### Response Example ```json { "id": "user123", "username": "johndoe", "email": "john.doe@example.com", "details": { "firstName": "John", "lastName": "Doe" } } ``` ``` -------------------------------- ### LibraryBootstrap::init() Initialization Source: https://github.com/estebanforge/hyperfields/blob/main/docs/library-bootstrap.md The `init()` method is the entry point for using HyperFields as a Composer dependency. It should be called once after the autoloader is loaded and before any HyperFields class is used. The method is idempotent. ```APIDOC ## POST /api/users ### Description Initializes the HyperFields library when used as a Composer dependency. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user to retrieve. #### Query Parameters - **include_details** (boolean) - Optional - Whether to include detailed user information. #### Request Body - **username** (string) - Required - The username for the new user. - **email** (string) - Required - The email address for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. - **details** (object) - Optional - Additional user details. #### Response Example ```json { "id": "user123", "username": "johndoe", "email": "john.doe@example.com", "details": { "firstName": "John", "lastName": "Doe" } } ``` ``` -------------------------------- ### Initialize Hyperfields Library Bootstrap Source: https://github.com/estebanforge/hyperfields/blob/main/docs/library-bootstrap.md Use this when your plugin's vendor directory is not in the standard WordPress path, such as in a monorepo. Define constants from the host plugin's known URL to ensure correct asset loading. ```php // my-plugin.php — constants are safe because plugin_dir_url() resolves // against WP's own plugin registration, not the filesystem path. \HyperFields\LibraryBootstrap::init([ 'plugin_file' => __FILE__, 'plugin_url' => plugin_dir_url(__FILE__) . 'vendor/estebanforge/hyperfields/', 'version' => '1.2.3', // optional: pin to your vendored version ]); ``` -------------------------------- ### Registering Admin Fields and Metaboxes Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Demonstrates how to create an options page and a standard WordPress metabox using the HyperFields API. ```php // Register an options page with fields $options = HyperFields::makeOptionPage('Site Settings', 'site-settings') ->setMenuTitle('Site Settings') ->setParentSlug('options-general.php'); $general = $options->addSection('general', 'General Settings', 'Basic site configuration'); $general->addField( HyperFields::makeField('text', 'site_tagline', 'Site Tagline')->setDefault('') ); $options->register(); // Register a post metabox field add_action('add_meta_boxes', function() { add_meta_box('custom_title', 'Custom Title', function($post) { $field = HyperFields::makeField('text', 'custom_title', 'Custom Title'); $value = PostField::for_post($post->ID, 'text', 'custom_title', 'Custom Title')->getValue(); echo ''; }, 'post'); }); ``` -------------------------------- ### Declare Color Field Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Declare a color field for hex color values. It defaults to '#ff0000' in this example. ```php $field = HyperFields::makeField('color', 'accent_color', 'Accent Color'); $field->setDefault('#ff0000'); ``` -------------------------------- ### Export Options to JSON Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields-examples.md Export one or more option groups to a JSON string. A prefix can be specified to only include keys starting with that prefix. ```php // Export one or more option groups to JSON $json = hf_export_options(['my_plugin_options'], 'myp_'); ``` -------------------------------- ### Performing a Dry-Run Diff for Import Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Use `diffOptions()` to preview changes before an actual import. It applies the same validation as `importOptions()` and reports changes and skipped options due to validation errors or whitelist misses. ```php $diff = ExportImport::diffOptions( $json, ['my_plugin_color', 'my_plugin_settings'], '', ['mode' => 'replace'] ); // $diff['changes'] — options that would change // $diff['skipped'] — options skipped (validation errors, whitelist misses) ``` -------------------------------- ### Initialize a Post Meta Container Source: https://github.com/estebanforge/hyperfields/blob/main/AGENTS.md Create a new meta box container for specific post types using the PostMetaContainer class. ```php use HyperFields\Container\PostMetaContainer; $container = new PostMetaContainer('my_meta_box', [ 'title' => 'Custom Fields', 'post_types' => ['post', 'page'], ]); $container->addField([...]); ``` -------------------------------- ### Interact with field storage Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Use field classes to get, set, or delete values across different storage contexts like options, posts, users, and terms. ```php // Get from options (default group 'hyperpress_options') $tagline = OptionField::forOption('site_tagline', 'text', 'site_tagline', 'Site Tagline')->getValue(); // Save to options (with type for sanitization) OptionField::forOption('site_tagline', 'text', 'site_tagline', 'Site Tagline')->setValue('Hello World'); // Get post meta by ID $title_override = PostField::forPost(123, 'text', 'custom_title', 'Custom Title')->getValue(); // Save user meta using user ID UserField::forUser(45, 'checkbox', 'onboarding_done', 'Onboarding Done')->setValue('1'); // Delete a term meta value TermField::forTerm(7, 'text', 'color', 'Color')->deleteValue(); ``` -------------------------------- ### Enqueue and Render Export/Import UI Assets Source: https://github.com/estebanforge/hyperfields/blob/main/docs/library-bootstrap.md Wire the ExportImportUI from admin_enqueue_scripts on your specific admin page only after LibraryBootstrap::init() has run. This ensures assets enqueue correctly. ```php add_action('admin_menu', function () { $hook = add_submenu_page( 'my-plugin', 'Data Tools', 'Data Tools', 'manage_options', 'my-plugin-data-tools', 'my_plugin_render_data_tools_page' ); add_action('admin_enqueue_scripts', function (string $suffix) use ($hook) { if ($suffix === $hook) { \HyperFields\Admin\ExportImportUI::enqueuePageAssets(); } }); }); function my_plugin_render_data_tools_page(): void { echo \HyperFields\Admin\ExportImportUI::render( options: ['my_plugin_options' => 'My Plugin Settings'], title: 'Data Tools', ); } ``` -------------------------------- ### Get Data by Path Utility Source: https://github.com/estebanforge/hyperfields/blob/main/docs/wp-settings-parity-implementation-plan.md A utility function to retrieve a value from a nested array structure using a dot-separated path. Provides a default value if the path does not exist. ```php getByPath(array $data, string $path, mixed $default = null): mixed ``` -------------------------------- ### Snapshot Options Data Source: https://github.com/estebanforge/hyperfields/blob/main/AGENTS.md Creates a snapshot of current options data, typically used for previewing changes before import. Allows specifying option names and an optional prefix. ```php snapshotOptions(array $optionNames, string $prefix = ''): string ``` -------------------------------- ### Declare Association Field Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Declare an association field for linking objects like posts or terms. This example sets it to allow multiple selections and link to 'post' and 'page' types. ```php $field = HyperFields::makeField('association', 'related_posts', 'Related Posts'); $field->setPostType(['post','page']); $field->setMultiple(true); ``` -------------------------------- ### Create an Options Page Source: https://github.com/estebanforge/hyperfields/blob/main/README.md Define a new options page and add a required text field to it. ```php use HyperFields\Field; use HyperFields\OptionsPage; $page = OptionsPage::make('My Settings', 'my-settings'); $page->addField( Field::make('text', 'site_title', 'Site Title') ->setDefault('My Site') ->setRequired() ); $page->register(); ``` -------------------------------- ### Registering Custom Options Pages Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Configures a custom options page with sections and fields using the fluent API. ```php $options = HyperFields::makeOptionPage('Site Settings', 'site-settings') ->setMenuTitle('Site Settings') ->setParentSlug('options-general.php') ->setIconUrl('dashicons-admin-generic'); $general = $options->addSection('general', 'General Settings', 'Basic site configuration'); $general->addField( HyperFields::makeField('text', 'site_tagline', 'Site Tagline') ->setDefault('') ); $options->register(); ``` -------------------------------- ### Restoring a Backup Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md How to restore a previously backed-up option using the backup key. ```APIDOC ## Restoring a Backup `importOptions()` automatically saves a transient backup of each option it overwrites (TTL: 1 hour). The backup key is returned in `$result['backup_keys']`. ### Method `ExportImport::restoreBackup` ### Parameters - `backup_key` (string) - Required - The key of the backup to restore. - `option_name` (string) - Required - The name of the option to restore. ### Example ```php use HyperFields\ExportImport; ExportImport::restoreBackup( $result['backup_keys']['my_plugin_options'], 'my_plugin_options' ); ``` ``` -------------------------------- ### Direct Field Class Operations Source: https://context7.com/estebanforge/hyperfields/llms.txt Utilize PostField, UserField, and TermField classes for direct meta operations. These classes offer built-in sanitization and methods to get, set, and delete values. ```php use HyperFields\PostField; use HyperFields\UserField; use HyperFields\TermField; // Post meta operations $field = PostField::forPost(123, 'text', 'custom_title', 'Custom Title'); $value = $field->getValue(); $field->setValue('New Title'); $field->deleteValue(); // User meta operations $userField = UserField::forUser(45, 'checkbox', 'newsletter_subscribed', 'Newsletter') ->setDefault(false); $subscribed = $userField->getValue(); $userField->setValue(true); // Term meta operations $termField = TermField::forTerm(7, 'color', 'category_color', 'Category Color') ->setDefault('#333333'); $color = $termField->getValue(); $termField->setValue('#ff5500'); ``` -------------------------------- ### HyperFields Targeting Syntax Quick Reference Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields-examples.md A quick reference for HyperFields targeting syntax, covering post, user, and term targeting. This includes targeting by ID, slug, type, role, and taxonomy, as well as combinations. Use this for reference when defining targeting rules. ```php // Post targeting ->where('post_type') // All posts of type ->wherePostId(123) // Specific post ID ->wherePostSlug('homepage') // Specific post slug ->wherePostIds([1, 2, 3]) // Multiple post IDs ->wherePostSlugs(['home', 'about']) // Multiple post slugs // User targeting ->where('administrator') // User role ->whereUserId(123) // Specific user ID ->whereUserIds([1, 2, 3]) // Multiple user IDs // Term targeting ->where('category') // Taxonomy ->whereTermId(123) // Specific term ID ->whereTermSlug('featured') // Specific term slug ->whereTermIds([1, 2, 3]) // Multiple term IDs ->whereTermSlugs(['featured', 'trending']) // Multiple term slugs ``` -------------------------------- ### Export and Import Options with Schema Validation in PHP Source: https://context7.com/estebanforge/hyperfields/llms.txt Manages plugin options by exporting them to JSON with schema validation and importing them back. Supports merging or replacing options and provides rollback capabilities via backup keys. Use `diffOptions` for a dry-run preview. ```php use HyperFields\ExportImport; // Export options to JSON with schema validation $schemaMap = [ 'site_tagline' => ['type' => 'string', 'max' => 255], 'accent_color' => ['type' => 'string', 'format' => 'hex_color'], 'items_per_page' => ['type' => 'integer', 'min' => 1, 'max' => 100], ]; $json = ExportImport::exportOptions( ['my_plugin_options'], // Option names to export 'myp_', // Only export keys with this prefix $schemaMap // Schema for validation ); // Save export to file file_put_contents('/tmp/settings-backup.json', $json); // Import options with validation $result = ExportImport::importOptions( $json, ['my_plugin_options'], // Allowed option names 'myp_', // Prefix filter ['mode' => 'merge'] // Merge or replace mode ); if ($result['success']) { echo 'Import successful!'; // Backup keys available for rollback $backupKey = $result['backup_keys']['my_plugin_options'] ?? null; } else { echo 'Import failed: ' . $result['message']; } // Dry-run diff before import $diff = ExportImport::diffOptions($json, ['my_plugin_options'], 'myp_'); // $diff['changes'] - options that would change // $diff['skipped'] - options skipped due to validation errors // Restore from backup if ($backupKey) { ExportImport::restoreBackup($backupKey, 'my_plugin_options'); } ``` -------------------------------- ### Create and Use Repeater Fields in PHP Source: https://context7.com/estebanforge/hyperfields/llms.txt Defines a repeater field for collecting multiple related data entries, such as social links. Includes setup, adding sub-fields, and retrieving/saving values. Ensure proper escaping when displaying retrieved data. ```php use HyperFields\HyperFields; // Create repeater for social links $repeater = HyperFields::makeRepeater('social_links', 'Social Links') ->setMinRows(0) ->setMaxRows(10) ->setCollapsible(true); $repeater->addSubField( HyperFields::makeField('text', 'label', 'Label') ->setPlaceholder('e.g., Twitter') ); $repeater->addSubField( HyperFields::makeField('url', 'url', 'URL') ->setPlaceholder('https://') ); $repeater->addSubField( HyperFields::makeField('text', 'icon', 'Icon Class') ->setPlaceholder('e.g., fa-twitter') ); // Add to section $section->addField($repeater); // Retrieve repeater values $social = hf_get_field('social_links', 'options', ['default' => []]); foreach ($social as $link) { echo ''; echo ' '; echo esc_html($link['label']); echo ''; } // Save repeater values $links = [ ['label' => 'Twitter', 'url' => 'https://twitter.com/example', 'icon' => 'fa-twitter'], ['label' => 'GitHub', 'url' => 'https://github.com/example', 'icon' => 'fa-github'], ]; hf_update_field('social_links', $links, 'options', ['type' => 'repeater']); ``` -------------------------------- ### Main API Class Usage Source: https://github.com/estebanforge/hyperfields/blob/main/AGENTS.md Demonstrates the primary methods of the HyperFields API class for registering options pages and retrieving saved option values. ```php HyperFields::registerOptionsPage([...]); HyperFields::getOptions('option_name', []); ``` -------------------------------- ### Public Facade Methods Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Provides a list of static methods available through the `HyperFields\[HyperFields]` facade for common data operations. ```APIDOC ## Public Facade (`HyperFields\HyperFields`) ### Description These are static methods provided by the `HyperFields` facade for performing various data export, import, and diff operations. ### Methods - `HyperFields::diffOptions(array $optionNames, string $prefix = '', array $schemaMap = []): array` - `HyperFields::exportPosts(array $postTypes, array $options = []): string` - `HyperFields::snapshotPosts(array $postTypes, array $options = []): array` - `HyperFields::importPosts(string $json, array $options = []): array` - `HyperFields::diffPosts(string $json, array $options = []): array` - `HyperFields::makeTransferManager(): Manager` ``` -------------------------------- ### Customize Export Envelope with SchemaConfig Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Use SchemaConfig to override default export envelope settings like type and schema version, and to inject custom top-level keys. This example sets a custom type, schema version 2, and adds site-specific information. ```php use HyperFields\Transfer\Manager; use HyperFields\Transfer\SchemaConfig; $manager = (new Manager())->withSchema(new SchemaConfig( type: 'my_plugin_manifest', schema_version: 2, extra: [ 'site' => [ 'url' => get_site_url(), 'environment' => defined('WP_ENVIRONMENT_TYPE') ? WP_ENVIRONMENT_TYPE : 'production', ], ], )); $bundle = $manager->export(); ``` -------------------------------- ### Create an Options Page Source: https://context7.com/estebanforge/hyperfields/llms.txt Define an admin settings page with sections and fields using the fluent API. The register method must be called to finalize the page creation. ```php use HyperFields\HyperFields; // Create a settings page under Settings menu $options = HyperFields::makeOptionPage('My Plugin Settings', 'my-plugin-settings') ->setMenuTitle('My Plugin') ->setParentSlug('options-general.php') ->setCapability('manage_options') ->setOptionName('my_plugin_options'); // Add a section with fields $general = $options->addSection('general', 'General Settings', 'Configure basic plugin options'); $general->addField( HyperFields::makeField('text', 'site_tagline', 'Site Tagline') ->setDefault('Welcome to my site') ->setPlaceholder('Enter tagline') ->setHelp('Displayed in the site header') ->setRequired() ); $general->addField( HyperFields::makeField('color', 'accent_color', 'Accent Color') ->setDefault('#0073aa') ); $general->addField( HyperFields::makeField('checkbox', 'enable_feature', 'Enable Premium Features') ->setDefault(false) ); // Register the page $options->register(); ``` -------------------------------- ### Execute bundle operations Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Performs export, diff, and import operations using the configured manager. ```php $bundle = $manager->export(); // or export(['options']) $diff = $manager->diff($bundle); $apply = $manager->import($bundle); ``` -------------------------------- ### Manage Pluggable Transfer Modules Source: https://context7.com/estebanforge/hyperfields/llms.txt Creates extensible transfer systems for custom export/import modules with support for custom schema envelopes. ```php use HyperFields\Transfer\Manager; use HyperFields\Transfer\SchemaConfig; use HyperFields\ExportImport; // Create manager with modules $manager = new Manager(); $manager->registerModule( 'settings', exporter: function (array $context): array { return ['json' => ExportImport::exportOptions($context['option_names'] ?? [])]; }, importer: function (array $payload, array $context): array { return ExportImport::importOptions( $payload['json'] ?? '', $context['allowed_options'] ?? [] ); }, differ: function (array $payload, array $context): array { return ExportImport::diffOptions( $payload['json'] ?? '', $context['allowed_options'] ?? [] ); } ); // Export all modules $bundle = $manager->export(); // Preview changes $diff = $manager->diff($bundle); // Import bundle $result = $manager->import($bundle); // Custom envelope schema $manager = (new Manager())->withSchema(new SchemaConfig( type: 'my_plugin_manifest', schema_version: 2, extra: [ 'site' => ['url' => get_site_url()], ], )); ``` -------------------------------- ### HyperFields Facade Methods Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Provides a list of static methods available through the HyperFields facade for performing operations like diffing, exporting, importing, and snapshotting posts and options. ```php HyperFields::diffOptions(...) HyperFields::exportPosts(...) HyperFields::snapshotPosts(...) HyperFields::importPosts(...) HyperFields::diffPosts(...) HyperFields::makeTransferManager() ``` -------------------------------- ### Import Options Data Source: https://github.com/estebanforge/hyperfields/blob/main/AGENTS.md Core logic for importing options data from a JSON string. Includes options for specifying allowed option names, a prefix, and automatically creates a backup. ```php importOptions(string $json, array $allowedOptionNames = [], string $prefix = ''): array ``` -------------------------------- ### Import Options from JSON Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields-examples.md Import options from a JSON string. It's recommended to restrict imports to your own options using the provided array and prefix. The result indicates success and may provide backup keys. ```php // Import from JSON — restrict to your own options $result = hf_import_options($json, ['my_plugin_options'], 'myp_'); if ($result['success']) { // Import succeeded; backup transient key available $backup_key = $result['backup_keys']['my_plugin_options'] ?? null; } else { echo $result['message']; // human-readable error } ``` -------------------------------- ### Register Data Tools Page Source: https://github.com/estebanforge/hyperfields/blob/main/AGENTS.md Register an admin page for data tools using either the facade or the procedural helper function. ```php add_action('admin_menu', function () { HyperFields\HyperFields::registerDataToolsPage( parentSlug: 'my-plugin', pageSlug: 'my-plugin-data-tools', options: ['my_plugin_options' => 'My Plugin Settings'], allowedImportOptions: ['my_plugin_options'], prefix: 'myp_', title: 'Data Tools', ); }); ``` ```php add_action('admin_menu', function () { hf_register_data_tools_page( parentSlug: 'my-plugin', pageSlug: 'my-plugin-data-tools', options: ['my_plugin_options' => 'My Plugin Settings'], ); }); ``` -------------------------------- ### Initialize HyperFields as Composer Dependency Source: https://github.com/estebanforge/hyperfields/blob/main/docs/library-bootstrap.md Call this once after your autoloader is loaded and before any HyperFields class is used. The method is idempotent. Ensure explicit `plugin_file` and `plugin_url` arguments are passed for vendored usage. ```php $autoload = plugin_dir_path(__FILE__) . 'vendor/autoload.php'; if (file_exists($autoload)) { require_once $autoload; } if (class_exists('\HyperFields\LibraryBootstrap')) { \HyperFields\LibraryBootstrap::init([ 'plugin_file' => __FILE__, 'plugin_url' => plugin_dir_url(__FILE__) . 'vendor/estebanforge/hyperfields/', ]); } ``` -------------------------------- ### Restore Options from Backup Source: https://github.com/estebanforge/hyperfields/blob/main/AGENTS.md Restores options data from a transient backup using a provided backup key and the specific option name. ```php restoreBackup(string $backupKey, string $optionName): bool ``` -------------------------------- ### Use Procedural Helper Functions Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Quickly validate values or detect types using global helper functions instead of the class API. ```php // Validate a single value $error = hf_validate_value('field_name', $value, ['type' => 'string', 'max' => 255]); // Validate a map $errors = hf_validate_schema($values, $schemaMap, 'prefix'); // Boolean check $ok = hf_is_valid($value, ['type' => 'string', 'format' => 'email']); // Detect type $type = hf_detect_type($value); ``` -------------------------------- ### Plugin Settings Schema and Validation Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Demonstrates defining a schema for plugin settings and using HyperFields for export, import, and server-side validation. ```APIDOC ## Class: MyPluginSettings ### Description This class defines a schema for WordPress plugin settings and provides methods for exporting, importing, and validating these settings using HyperFields. ### Schema Definition ```php class MyPluginSettings { private const SCHEMA = [ 'my_plugin_api_url' => ['type' => 'string', 'max' => 2083, 'format' => 'url'], 'my_plugin_api_key' => ['type' => 'string', 'max' => 255], 'my_plugin_enabled' => ['type' => 'string', 'enum' => ['yes', 'no']], 'my_plugin_max_retries'=> ['type' => 'string', 'pattern' => '/^\d{1,2}$/'], 'my_plugin_color' => ['type' => 'string', 'format' => 'hex_color'], 'my_plugin_recipients' => ['type' => 'string', 'max' => 2000, 'format' => 'email_csv_or_empty'], ]; public function export(): string { return ExportImport::exportOptions( array_keys(self::SCHEMA), '', self::SCHEMA ); } public function import(string $json): array { // HyperFields validates every option against its _schema automatically. return ExportImport::importOptions( $json, array_keys(self::SCHEMA), '', ['mode' => 'replace'] ); } public function validate_before_save(array $values): array { // Use SchemaValidator directly for form/REST validation. return SchemaValidator::validateMap($values, self::SCHEMA); } } ``` ### Import Process Explanation 1. HyperFields parses the JSON input. 2. It checks for a typed-node envelope (`value` + `_schema`). 3. It validates the value against the schema's `type`, `format`, and `max` constraints. 4. If all checks pass, the value is saved. 5. If any check fails, the option is skipped with an error, and import continues. ### Server-side Form Validation Use `SchemaValidator::validateMap` or `hf_validate_schema` for validating user input before saving. #### Example using `hf_validate_schema`: ```php // In your settings save handler: $errors = hf_validate_schema($_POST['settings'], MyPluginSettings::SCHEMA); if (!empty($errors)) { foreach ($errors as $error) { add_settings_error('my_plugin', 'validation', $error); } return; } // All valid — save. ``` ``` -------------------------------- ### Enable Compact Input Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields-examples.md Define constants to enable compact input for options pages, which helps avoid PHP's 'max_input_vars' limit by serializing fields into a single POST variable. ```php define('HYPERPRESS_COMPACT_INPUT', true); define('HYPERPRESS_COMPACT_INPUT_KEY', 'hyperpress_compact_input'); // optional, default shown ``` -------------------------------- ### WP Settings API Compatibility Source: https://context7.com/estebanforge/hyperfields/llms.txt This section demonstrates how to migrate existing WordPress Settings API configurations to HyperFields. ```APIDOC ## WP Settings API Compatibility Migrate existing Settings API configurations to HyperFields. ### Method ```php use HyperFields\HyperFields; // Register from compatibility configuration $page = HyperFields::registerWPSettingsCompatibilityPage([ 'page_title' => 'Plugin Settings', 'menu_slug' => 'my-plugin-settings', 'option_name' => 'my_plugin_options', 'capability' => 'manage_options', 'sections' => [ [ 'id' => 'general', 'title' => 'General', 'fields' => [ [ 'id' => 'api_key', 'title' => 'API Key', 'type' => 'text', 'sanitize' => 'sanitize_text_field', ], [ 'id' => 'enable_logging', 'title' => 'Enable Logging', 'type' => 'checkbox', ], ], ], ], ]); ``` ### Parameters #### Request Body - **page_title** (string) - Required - The title for the settings page. - **menu_slug** (string) - Required - The unique slug for the menu item. - **option_name** (string) - Required - The name of the WordPress option to store the settings. - **capability** (string) - Required - The capability required to access the settings page. - **sections** (array) - Required - An array of sections for the settings page. - **id** (string) - Required - The unique ID for the section. - **title** (string) - Required - The title of the section. - **fields** (array) - Required - An array of fields within the section. - **id** (string) - Required - The unique ID for the field. - **title** (string) - Required - The label for the field. - **type** (string) - Required - The type of the field (e.g., 'text', 'checkbox'). - **sanitize** (string) - Optional - The sanitization callback function. ``` -------------------------------- ### Enforce module-level import policies Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Demonstrates filtering module decisions and injecting context flags during the import process. ```php use HyperFields\Transfer\Manager; // Skip selected modules in production. add_filter( 'hyperfields/transfer_manager/import/module_decision', static function (array $decision, string $moduleKey, $payload, array $context, array $bundle): array { if (wp_get_environment_type() === 'production' && in_array($moduleKey, ['emails', 'content'], true)) { return [ 'action' => 'skip', 'reason' => 'blocked_in_production', ]; } return $decision; }, 10, 5 ); // Inject per-module flags consumed by your importer callback. add_filter( 'hyperfields/transfer_manager/import/module_context', static function (array $context, string $moduleKey, $payload, array $bundle): array { $context['strict_mode'] = ($moduleKey === 'content'); return $context; }, 10, 4 ); ``` -------------------------------- ### Custom Export Envelope with SchemaConfig Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Demonstrates how to use SchemaConfig to customize the export envelope, including setting custom types, schema versions, and adding extra top-level keys. ```APIDOC ## Custom Export Envelope (SchemaConfig) ### Description By default, the export envelope uses HyperFields type identifiers and schema version 1. The `SchemaConfig` class allows you to override these defaults and inject additional top-level keys into the export bundle. ### Method `Manager::withSchema(SchemaConfig $config)` ### Parameters #### Request Body (for `SchemaConfig` constructor) - **type** (string) - Optional - Overrides the default export type identifier. - **schema_version** (int) - Optional - Overrides the default schema version. - **extra** (array) - Optional - An associative array of additional top-level keys to include in the export bundle. Reserved keys (`schema_version`, `type`, `generated_at`, `modules`, `errors`) are silently stripped if present in `extra`. ### Request Example ```php use HyperFields\Transfer\Manager; use HyperFields\Transfer\SchemaConfig; $manager = (new Manager())->withSchema(new SchemaConfig( type: 'my_plugin_manifest', schema_version: 2, extra: [ 'site' => [ 'url' => get_site_url(), 'environment' => defined('WP_ENVIRONMENT_TYPE') ? WP_ENVIRONMENT_TYPE : 'production', ], ], )); $bundle = $manager->export(); ``` ### Response Example (Bundle Shape) ```json { "site": { "url": "https://example.com", "environment": "staging" }, "schema_version": 2, "type": "my_plugin_manifest", "generated_at": "...", "modules": { "options": {} }, "errors": [] } ``` ### Notes - The `withSchema()` method returns the `Manager` instance, allowing for fluent chaining. - Omitting the call to `withSchema()` preserves the original default envelope settings. ``` -------------------------------- ### ExportImportUI::renderConfigured Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Renders the export/import UI using a configuration object. ```APIDOC ## ExportImportUI::renderConfigured For immutable config-driven wiring, pass an `ExportImportPageConfig` object. ### Method `ExportImportUI::renderConfigured` ### Parameters - `config` (ExportImportPageConfig) - Required - An instance of `ExportImportPageConfig`. ### Example ```php use HyperFields\Admin\ExportImportPageConfig; use HyperFields\Admin\ExportImportUI; $config = new ExportImportPageConfig( options: ['my_plugin_options' => 'My Plugin Settings'], optionGroups: ['my_plugin_options' => 'Core'], prefix: 'myp_', ); echo ExportImportUI::renderConfigured($config); ``` ``` -------------------------------- ### Load Composer Autoloader Source: https://github.com/estebanforge/hyperfields/blob/main/README.md Include the autoloader in your project to initialize library classes. ```php require_once __DIR__ . '/vendor/autoload.php'; ``` -------------------------------- ### Import WordPress Posts and CPTs with HyperFields Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Imports post-like records, with options to create missing posts, update existing ones, and control meta data inclusion and merging. ```php $result = ContentExportImport::importPosts( $json, [ 'allowed_post_types' => ['page', 'my_cpt'], 'dry_run' => false, 'create_missing' => true, 'update_existing' => true, 'include_meta' => true, 'meta_mode' => 'merge', // 'merge' | 'replace' 'include_private_meta' => false, 'include_meta_keys' => [], 'exclude_meta_keys' => ['_edit_lock'], 'normalization_profile' => '', // optional profile key for row normalization hooks ] ); ``` -------------------------------- ### Register Data Tools Page with Procedural Helper Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields-examples.md An alternative to the class method, this procedural helper can be used inside 'admin_menu' to register a Data Tools page. It requires the parent slug, page slug, and options. ```php add_action('admin_menu', function () { hf_register_data_tools_page( parentSlug: 'my-plugin', pageSlug: 'my-plugin-data-tools', options: ['my_plugin_options' => 'My Plugin Settings'], ); }); ``` -------------------------------- ### Register Data Tools Admin Page via Helper Function Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Register a data tools admin page using the `hf_register_data_tools_page` helper function. This provides a concise way to set up the admin page. ```php add_action('admin_menu', function () { hf_register_data_tools_page( parentSlug: 'my-plugin', pageSlug: 'my-plugin-data-tools', options: ['my_plugin_options' => 'My Plugin Settings'], prefix: 'myp_', title: 'Data Tools', ); }); ``` -------------------------------- ### Programmatic Export and Import Source: https://github.com/estebanforge/hyperfields/blob/main/AGENTS.md Perform export and import operations programmatically, including backup restoration. ```php // Export to JSON $json = hf_export_options(['my_plugin_options'], 'myp_'); // Import from JSON (returns ['success' => bool, 'message' => string, 'backup_keys' => [...]]) $result = hf_import_options($json, ['my_plugin_options'], 'myp_'); // Restore from backup if import went wrong if (!$result['success']) { HyperFields\ExportImport::restoreBackup($result['backup_keys']['my_plugin_options'], 'my_plugin_options'); } ``` -------------------------------- ### Register Data Tools Admin Page Directly via Class Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Register a data tools admin page by directly using the `ExportImportUI` class. This offers more explicit control over the registration process. ```php use HyperFields\Admin\ExportImportUI; add_action('admin_menu', function () { ExportImportUI::registerPage( parentSlug: 'my-plugin', pageSlug: 'my-plugin-data-tools', options: ['my_plugin_options' => 'My Plugin Settings'], allowedImportOptions: ['my_plugin_options'], prefix: 'myp_', title: 'Data Tools', capability: 'manage_options', ); }); ``` -------------------------------- ### Restore Options from Backup Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields-examples.md Restore options from a transient backup if an import operation failed. This function requires the backup key and the option group name. ```php // Restore from transient backup if something went wrong HyperFields\ExportImport::restoreBackup( $result['backup_keys']['my_plugin_options'], 'my_plugin_options' ); ``` -------------------------------- ### Create a Snapshot of WordPress Posts with HyperFields Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Generates a snapshot of specified post types, useful for external comparison workflows. ```php $snapshot = ContentExportImport::snapshotPosts(['page', 'my_cpt']); ``` -------------------------------- ### Initialize WP Code Editor Source: https://github.com/estebanforge/hyperfields/blob/main/docs/wp-settings-parity-implementation-plan.md Enqueues necessary assets and initializes a code editor instance using `wp_enqueue_code_editor`. This is used for the `code-editor` option type. ```php wp_enqueue_code_editor(['type' => 'application/json']); ``` -------------------------------- ### Generate a Dry-Run Diff for Importing WordPress Content Source: https://github.com/estebanforge/hyperfields/blob/main/docs/transfer-and-content-export-import.md Compares incoming JSON content against existing posts without performing any writes, showing a preview of changes. ```php $preview = ContentExportImport::diffPosts($json, [ 'allowed_post_types' => ['page', 'my_cpt'], ]); ``` -------------------------------- ### Run HyperFields Tests Source: https://github.com/estebanforge/hyperfields/blob/main/README.md Execute various test suites using the configured Composer scripts. ```bash composer run test composer run test:unit composer run test:integration composer run test:coverage composer run test:xdebug ``` -------------------------------- ### Execute Action After Import Result Notice Source: https://github.com/estebanforge/hyperfields/blob/main/docs/hyperfields.md Perform custom actions after the import result notice is displayed by hooking into the `hyperfields/import/ui_notice_after` action. This allows for executing code, such as displaying additional status panels, based on the import outcome. ```php add_action('hyperfields/import/ui_notice_after', function (array $importResult, bool $importSuccess): void { if ($importSuccess) { echo '
Additional status panel.