OptStack Field Usage Guide
This document provides a comprehensive guide on how to use fields in OptStack. Fields are the building blocks of your options pages, meta boxes, and custom data structures.
Basic Field Syntax
Fields are defined using the field() method on a stack, tab, or group:
$stack->field('field_id', [
'type' => 'text',
'label' => 'Field Label',
'default' => 'Default value',
'description' => 'Help text for the field',
]);Field in a Tab
$stack->tab('general', function ($tab) {
$tab->field('site_title', [
'type' => 'text',
'label' => 'Site Title',
]);
});Field in a Group
$stack->group('settings', function ($group) {
$group->field('enable_feature', [
'type' => 'toggle',
'label' => 'Enable Feature',
]);
}, ['label' => 'Settings']);Common Field Properties
All fields share these common properties:
| Property | Type | Description |
|---|---|---|
type | string | Required. The field type (e.g., 'text', 'number', 'toggle') |
label | string | The field label displayed to users |
description | string | Help text shown below the field |
default | mixed | Default value when no value is saved |
attributes | array | Additional field-specific attributes |
conditions | array | Conditional logic rules for showing/hiding the field |
Example with All Common Properties
$stack->field('example_field', [
'type' => 'text',
'label' => 'Example Field',
'description' => 'This is a helpful description',
'default' => 'Default text',
'attributes' => [
'placeholder' => 'Enter text...',
'maxlength' => 100,
],
'conditions' => [
['field' => 'enable_feature', 'operator' => '==', 'value' => true],
],
]);Available Field Types
OptStack supports the following field types. Click each link for detailed documentation:
Input Fields
- text - Single-line text input
- textarea - Multi-line text input
- number - Numeric input with min/max/step
- email - Email address input
- url - URL input with validation
Selection Fields
- select - Dropdown select menu
- radio - Radio button group
- radio-image - Visual radio buttons with images
- checkbox-group - Multiple checkbox selection
- toggle - On/off switch
Visual Fields
- color - Color picker with optional alpha
- media - WordPress media library picker
- range - Slider range input
Rich Content Fields
- wysiwyg - WordPress visual editor
- code - Code editor with syntax highlighting
- typography - Complete typography controls
Advanced Fields
- visual_builder - Drag-and-drop visual content builder
Conditional Logic
Fields can be shown or hidden based on other field values using the conditions property:
Basic Condition
$stack->field('message', [
'type' => 'textarea',
'label' => 'Message',
'conditions' => [
['field' => 'enable_message', 'operator' => '==', 'value' => true],
],
]);Available Operators
| Operator | Description |
|---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
contains | Contains value (for arrays) |
not_contains | Does not contain value |
Multiple Conditions (AND)
'conditions' => [
['field' => 'enable_feature', 'operator' => '==', 'value' => true],
['field' => 'feature_type', 'operator' => '!=', 'value' => 'none'],
],Referencing Fields in Groups
When referencing a field inside a group from the same group, use just the field name:
$stack->group('settings', function ($group) {
$group->field('enable', [
'type' => 'toggle',
'label' => 'Enable',
]);
$group->field('value', [
'type' => 'text',
'label' => 'Value',
'conditions' => [
['field' => 'enable', 'operator' => '==', 'value' => true],
],
]);
});Field Attributes
The attributes property allows you to pass additional configuration specific to each field type. Common attributes include:
Input Attributes
'attributes' => [
'placeholder' => 'Enter value...',
'maxlength' => 100,
'minlength' => 5,
'readonly' => true,
'disabled' => false,
]Number Attributes
'attributes' => [
'min' => 0,
'max' => 100,
'step' => 5,
'suffix' => 'px',
'prefix' => '$',
]Media Attributes
'attributes' => [
'allowedTypes' => ['image'],
'buttonText' => 'Select Image',
'multiple' => false,
]See individual field documentation for field-specific attributes.
Retrieving Field Values
Using OptStack::getField() (Recommended)
The OptStack::getField() method is the recommended way to retrieve single field values. It supports dot notation for nested fields and automatically binds the store for post/term/user contexts.
// Basic syntax
OptStack::getField(
string $stackId, // Stack identifier
string $key, // Field key (supports dot notation)
mixed $default, // Default value if not found
?int $objectId // Object ID (required for post/term/user contexts)
): mixedFor Options Pages
// Simple field
$site_name = OptStack::getField('site_settings', 'site_name', 'My Site');
// Nested field in a group (dot notation)
$logo = OptStack::getField('theme_options', 'identity.site_logo', '');
$primary_color = OptStack::getField('theme_options', 'colors.primary', '#3b82f6');
$sticky = OptStack::getField('theme_options', 'header_layout.sticky', true);
// Deeply nested field
$h1_size = OptStack::getField('theme_options', 'typography.heading_sizes.h1_size', 48);For Post Meta
// Simple field
$price = OptStack::getField('product_data', 'price', 0, $post_id);
// Nested field
$meta_title = OptStack::getField('product_data', 'seo.meta_title', '', $post_id);
// Multiple fields
$regular_price = OptStack::getField('product_data', 'pricing.regular_price', 0, $post_id);
$sale_price = OptStack::getField('product_data', 'pricing.sale_price', 0, $post_id);For Term Meta
// Simple field
$icon = OptStack::getField('category_settings', 'icon', '', $term_id);
// Nested field
$display_mode = OptStack::getField('category_settings', 'display.mode', 'grid', $term_id);For User Meta
// Simple field
$bio = OptStack::getField('user_profile', 'bio', '', $user_id);
// Nested field
$twitter = OptStack::getField('user_profile', 'social.twitter', '', $user_id);Using OptStack::updateField()
Update a single field value with automatic searchable field sync:
// Basic syntax
OptStack::updateField(
string $stackId, // Stack identifier
string $key, // Field key (supports dot notation)
mixed $value, // New value
?int $objectId // Object ID (required for post/term/user contexts)
): bool
// Examples
OptStack::updateField('product_data', 'price', 99.99, $post_id);
OptStack::updateField('product_data', 'seo.meta_title', 'New Title', $post_id);
OptStack::updateField('theme_options', 'colors.primary', '#3b82f6');Creating a Theme Helper Function (Recommended)
For cleaner code in your theme, create a wrapper function that uses OptStack::getField():
use OptStack\OptStack;
/**
* Get a theme option value.
*
* @param string $key Field key (supports dot notation for nested fields)
* @param mixed $default Default value if not found
* @return mixed
*/
function mytheme_option(string $key, mixed $default = null): mixed
{
return OptStack::getField('theme_options', $key, $default);
}
/**
* Get a post meta value.
*
* @param string $key Field key (supports dot notation)
* @param mixed $default Default value if not found
* @param int|null $post_id Post ID (defaults to current post)
* @return mixed
*/
function mytheme_post_meta(string $key, mixed $default = null, ?int $post_id = null): mixed
{
$post_id = $post_id ?? get_the_ID();
return OptStack::getField('post_options', $key, $default, $post_id);
}Usage in Templates
// In header.php
$logo = mytheme_option('identity.site_logo');
$sticky_header = mytheme_option('header_layout.sticky', true);
if ($logo) {
echo '<img src="' . esc_url(wp_get_attachment_url($logo)) . '" alt="Logo">';
}
// In single.php
$show_author = mytheme_post_meta('display.show_author', true);
$custom_title = mytheme_post_meta('seo.custom_title', get_the_title());Complete Theme Functions Example
/**
* Theme helper functions for OptStack
* Add this to your theme's functions.php
*/
use OptStack\OptStack;
/**
* Get theme option with caching.
*/
function mytheme_option(string $key, mixed $default = null): mixed
{
static $cache = [];
if (!isset($cache[$key])) {
$cache[$key] = OptStack::getField('theme_options', $key, $default);
}
return $cache[$key];
}
/**
* Update a theme option.
*/
function mytheme_update_option(string $key, mixed $value): bool
{
return OptStack::updateField('theme_options', $key, $value);
}
/**
* Check if a theme option is enabled (for toggles).
*/
function mytheme_is_enabled(string $key): bool
{
return (bool) mytheme_option($key, false);
}
// Usage examples
if (mytheme_is_enabled('header_layout.sticky')) {
// Add sticky header class
}
$primary_color = mytheme_option('colors.primary', '#3b82f6');
$font_size = mytheme_option('typography.body_font.fontSize', 16);Direct WordPress Functions (Alternative)
You can also use native WordPress functions directly (without OptStack helpers):
For Options Pages
// Get all options
$options = get_option('your_stack_id', []);
// Get specific value
$value = $options['field_id'] ?? 'default';
// For grouped fields
$grouped_value = $options['group_id']['field_id'] ?? 'default';Manual Dot Notation Helper
If you prefer not to use OptStack::getField(), here's a standalone helper:
function my_option(string $key, mixed $default = null): mixed
{
$options = get_option('my_options', []);
$keys = explode('.', $key);
$value = $options;
foreach ($keys as $k) {
if (!isset($value[$k])) {
return $default;
}
$value = $value[$k];
}
return $value;
}
// Usage
$logo = my_option('identity.site_logo');
$sticky = my_option('header_layout.sticky', true);For Post Meta
// Get post meta
$value = get_post_meta($post_id, 'field_id', true);For Term Meta
// Get term meta
$value = get_term_meta($term_id, 'field_id', true);For User Meta
// Get user meta
$value = get_user_meta($user_id, 'field_id', true);Method Comparison
| Method | Best For | Dot Notation | Auto Store Binding |
|---|---|---|---|
OptStack::getField() | Single field retrieval | ✅ Yes | ✅ Yes |
OptStack::updateField() | Single field update | ✅ Yes | ✅ Yes |
get_option() / get_post_meta() | Direct WP access | ❌ No | N/A |
Best Practices
-
Use descriptive field IDs: Use snake_case and be descriptive (e.g.,
header_background_colornothbc) -
Always provide defaults: Set sensible default values to prevent empty states
-
Group related fields: Use groups to organize related fields together
-
Use descriptions wisely: Provide helpful context without being verbose
-
Validate on retrieval: Always validate field values when using them in templates
-
Use conditional logic: Hide irrelevant fields to simplify the UI