iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Settings

WordPress’s Settings API is the standard way to add admin pages and persist options. register_setting + add_settings_section + add_settings_field + options_* functions cover the whole flow.

A real Settings page

EXAMPLE
<?php
add_action('admin_menu', function () {
    add_options_page(
        'My Plugin',
        'My Plugin',
        'manage_options',
        'my-plugin',
        'my_plugin_render',
    );
});

add_action('admin_init', function () {
    register_setting('my_plugin_group', 'my_plugin_options', [
        'type'              => 'array',
        'sanitize_callback' => 'my_plugin_sanitize',
        'default'           => [
            'enabled'   => true,
            'api_key'   => '',
            'log_level' => 'info',
        ],
    ]);

    add_settings_section(
        'my_plugin_main',
        'General',
        function () { echo '<p>Plugin settings.</p>'; },
        'my-plugin',
    );

    add_settings_field('enabled', 'Enabled', 'my_plugin_field_enabled', 'my-plugin', 'my_plugin_main');
    add_settings_field('api_key', 'API key',  'my_plugin_field_api_key', 'my-plugin', 'my_plugin_main');
});

function my_plugin_render() {
    ?>
    <div class="wrap">
        <h1>My Plugin</h1>
        <form action="options.php" method="post">
            <?php settings_fields('my_plugin_group'); ?>
            <?php do_settings_sections('my-plugin'); ?>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

function my_plugin_field_enabled() {
    $opts = get_option('my_plugin_options');
    printf(
        '<input type="checkbox" name="my_plugin_options[enabled]" value="1" %s>',
        checked(!empty($opts['enabled']), true, false)
    );
}

function my_plugin_field_api_key() {
    $opts = get_option('my_plugin_options');
    printf(
        '<input type="text" class="regular-text" name="my_plugin_options[api_key]" value="%s">',
        esc_attr($opts['api_key'])
    );
}

function my_plugin_sanitize($input) {
    return [
        'enabled'   => !empty($input['enabled']),
        'api_key'   => sanitize_text_field($input['api_key']),
        'log_level' => in_array($input['log_level'] ?? '', ['debug','info','warn','error'], true)
            ? $input['log_level'] : 'info',
    ];
}

Why it matters

Always pass a sanitize_callback. WP doesn’t sanitise stored options for you — whatever the form sends is what gets serialised into wp_options.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// /wp-admin > Settings — site title, URL, permalinks, discussion, etc.
Try it Yourself »

Discussion

Loading…