How to build a Settings Page in WordPress.

Outline

To build a WordPress settings page, you can follow these steps:

  1. Create a new plugin or add a new file to an existing plugin.
  2. Add a menu page using the add_menu_page function. This function allows you to add a top-level menu page to the WordPress admin panel.
  3. Use the add_settings_section and add_settings_field functions to create form fields for your plugin’s settings.
  4. Register your plugin’s settings using the register_setting function.
  5. Use the settings_fields and do_settings_sections functions to output your form fields in the correct format.
  6. Add a submit button to your form using the submit_button function.
  7. Save any changes to the plugin’s settings by handling the form submission using the update_option function.

Example for Single Text Field

Here is an example of a basic plugin that adds a menu page and displays a form with a single text field:

<?php

// Add a top-level menu page
add_menu_page(
    'My Plugin Settings',
    'My Plugin',
    'manage_options',
    'my-plugin',
    'my_plugin_settings_page'
);

// Callback function for the plugin's settings page
function my_plugin_settings_page() {
    ?>
    <div class="wrap">
        <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
        <form action="options.php" method="post">
            <?php
            // Output nonce, action, and option_page fields for a settings page
            settings_fields( 'my_plugin_options' );
            // Output setting sections and fields
            do_settings_sections( 'my_plugin' );
            // Submit button
            submit_button();
            ?>
        </form>
    </div>
    <?php
}

// Register a new setting and its sanitization callback
register_setting(
    'my_plugin_options',
    'my_plugin_setting',
    'sanitize_my_plugin_setting'
);

// Add a new settings section
add_settings_section(
    'my_plugin_section',
    'My Plugin Settings',
    '',
    'my_plugin'
);

// Add a new field to the settings section
add_settings_field(
    'my_plugin_field',
    'My Setting',
    'render_my_plugin_field',
    'my_plugin',
    'my_plugin_section'
);

// Callback function to render the settings field
function render_my_plugin_field() {
    // Get the current value of the setting
    $setting = get_option( 'my_plugin_setting' );
    ?>
    <input type="text" name="my_plugin_setting" value="<?php echo esc_attr( $setting ); ?>">
    <?php
}

// Sanitization callback for the setting
function sanitize_my_plugin_setting( $value ) {
    return sanitize_text_field( $value );
}