Skip to content

Use in Options Setting

Wapiclo edited this page Dec 4, 2025 · 2 revisions

This guide demonstrates how to create custom options/settings pages with Wapic Fields in the WordPress admin.

Complete Example

Below is a complete example showing how to create an options page with custom fields, including validation and sanitization.

<?php
/**
 * Example Option Page using Wapic Fields
 *
 * This demonstrates how to create a custom settings page
 * in WordPress admin with Wapic Fields.
 *
 * @package Wapic_Fields
 */

namespace Wapic_Fields\Example;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

use Wapic_Fields\Field;

class Example_Option {

    /**
     * Page ID
     *
     * @var string
     */
    private $id = 'wapic-field-option';

    /**
     * Constructor - Register hooks
     */
    public function __construct() {
        add_action( 'admin_menu', array( $this, 'register' ) );
        add_action( 'admin_init', array( $this, 'save' ) );
    }

    /**
     * Register Admin Menu Page
     *
     * Creates a settings page in the WordPress admin menu.
     */
    public function register() {
        add_menu_page(
            esc_html__( 'Wapic Fields Options Example', 'wapic-field' ), // Page title
            esc_html__( 'Wapic Fields', 'wapic-field' ),                 // Menu title
            'manage_options',                                             // Capability
            $this->id,                                                    // Menu slug
            array( $this, 'render' ),                                     // Callback function
            'dashicons-admin-generic',                                    // Icon
            9999                                                          // Position
        );
    }

    /**
     * Render the Settings Page
     *
     * Displays the settings form with fields.
     */
    public function render() {

        // Start the controls panel
        Field::start_controls_panel(
            array(
                'title' => esc_html__( 'Wapic Fields Options Example', 'wapic-field' ),
                'id'    => $this->id,
                'type'  => 'setting',
            )
        );

        // HTML field for description
        Field::add_control(
            array(
                'type'  => 'html',
                'value' => '<p>' . esc_html__( 'Configure your settings below.', 'wapic-field' ) . '</p>',
            )
        );

        // Text field
        Field::add_control(
            array(
                'id'    => '_sample_text',
                'type'  => 'text',
                'label' => esc_html__( 'Text Field', 'wapic-field' ),
                'value' => get_option( '_sample_text' ),
            )
        );

        // Email field
        Field::add_control(
            array(
                'id'    => '_sample_email',
                'type'  => 'email',
                'label' => esc_html__( 'Email Address', 'wapic-field' ),
                'value' => get_option( '_sample_email' ),
            )
        );

        // Number field with attributes
        Field::add_control(
            array(
                'id'         => '_sample_number',
                'type'       => 'number',
                'label'      => esc_html__( 'Number Field', 'wapic-field' ),
                'value'      => get_option( '_sample_number' ),
                'attributes' => array(
                    'min' => 0,
                    'max' => 100,
                ),
            )
        );

        // End the controls panel
        Field::end_controls_panel( array( 'type' => 'setting' ) );
    }

    /**
     * Register and Sanitize Settings
     *
     * Registers each field with WordPress Settings API
     * and applies validation and sanitization.
     */
    public function save() {

        // Define all fields and their types
        $fields = array(
            '_sample_text'   => 'text',
            '_sample_email'  => 'email',
            '_sample_number' => 'number',
        );

        // Register each field
        foreach ( $fields as $field_name => $field_type ) {
            register_setting(
                $this->id,
                $field_name,
                array(
                    'sanitize_callback' => function ( $value, $option = '' ) use ( $field_type, $field_name ) {

                        // Skip validation if field is hidden (conditional logic)
                        if ( isset( $_POST[ $field_name . '_is_hidden' ] ) && $_POST[ $field_name . '_is_hidden' ] === '1' ) {
                            return Field::sanitize_value( $field_type, $value );
                        }

                        // Validate the value
                        $validation = Field::validate_value( $field_type, $value );

                        if ( ! empty( $validation ) ) {
                            // Validation failed - show error and return old value
                            add_settings_error( $this->id, 'validation_error', $validation, 'error' );
                            return get_option( $field_name, '' );
                        }

                        // Validation passed - sanitize and return
                        return Field::sanitize_value( $field_type, $value );
                    },
                )
            );
        }
    }
}

// Initialize the options page
new Example_Option();

Retrieving Saved Values

To display or retrieve the saved option values in your theme or plugin, use the standard WordPress get_option() function:

<?php
$sample_text   = get_option( '_sample_text' );
$sample_email  = get_option( '_sample_email' );
$sample_number = get_option( '_sample_number' );

// Example output
echo '<p>' . esc_html( $sample_text ) . '</p>';
echo '<p>Email: <a href="mailto:' . esc_attr( $sample_email ) . '">' . esc_html( $sample_email ) . '</a></p>';
echo '<p>Number: ' . esc_html( $sample_number ) . '</p>';

With Default Values

You can provide a default value as the second parameter:

<?php
$sample_text = get_option( '_sample_text', 'Default text' );
echo '<p>' . esc_html( $sample_text ) . '</p>';

Key Points

  1. Settings API: Uses WordPress Settings API for proper integration
  2. Validation: Validates input using Field::validate_value()
  3. Sanitization: Sanitizes input using Field::sanitize_value()
  4. Error Handling: Displays validation errors using add_settings_error()
  5. Conditional Logic: Supports hidden fields with conditional logic
  6. Capability Check: Only users with manage_options capability can access the page

Customization

Change Menu Position

Modify the add_menu_page() parameters to customize the menu:

add_menu_page(
    'Page Title',           // Browser page title
    'Menu Title',           // Menu item title
    'manage_options',       // Required capability
    'my-custom-page',       // Menu slug (unique)
    array( $this, 'render' ), // Callback function
    'dashicons-admin-site', // Menu icon (dashicons)
    25                      // Position (lower = higher in menu)
);

Add as Submenu

To add the page as a submenu under an existing menu, use add_submenu_page():

add_submenu_page(
    'options-general.php',  // Parent slug (Settings menu)
    'Page Title',
    'Menu Title',
    'manage_options',
    'my-custom-page',
    array( $this, 'render' )
);

Common parent slugs:

  • 'options-general.php' - Settings
  • 'themes.php' - Appearance
  • 'plugins.php' - Plugins
  • 'tools.php' - Tools
  • 'edit.php' - Posts

Advanced: Storing Options in a Single Row

For better performance and cleaner database structure, you can store all options in a single database row as an array.

See the Single Row Options Guide for details.

Next Steps

Clone this wiki locally