Performance: Settings API
This affects the admin page load speed and responsiveness when managing settings in WordPress.
<?php add_action('admin_init', function() { register_setting('my_plugin_options', 'my_plugin_option'); add_settings_section('my_plugin_section', 'My Plugin Settings', null, 'my_plugin'); add_settings_field('my_plugin_option', 'Option', function() { $value = get_option('my_plugin_option'); echo '<input type="text" name="my_plugin_option" value="' . esc_attr($value) . '">'; }, 'my_plugin', 'my_plugin_section'); }); add_action('admin_menu', function() { add_options_page('My Plugin', 'My Plugin', 'manage_options', 'my-plugin', function() { echo '<form method="post" action="options.php">'; settings_fields('my_plugin_options'); do_settings_sections('my_plugin'); submit_button(); echo '</form>'; }); }); ?>
<?php add_action('admin_menu', function() { add_options_page('My Plugin', 'My Plugin', 'manage_options', 'my-plugin', function() { echo '<form method="post" action="options.php">'; settings_fields('my_plugin_options'); do_settings_sections('my_plugin'); echo '<input type="text" name="my_plugin_option" value="' . get_option('my_plugin_option') . '">'; submit_button(); echo '</form>'; }); }); register_setting('my_plugin_options', 'my_plugin_option'); ?>
| Pattern | Option Lookups | PHP Processing | HTML Output Complexity | Verdict |
|---|---|---|---|---|
| Manual form fields without Settings API | Multiple redundant | High due to repeated calls | Unstructured and verbose | [X] Bad |
| Proper use of Settings API | Batched and cached | Lower due to organized calls | Clean and minimal | [OK] Good |
register_setting() registers a setting group and option name for saving options.add_settings_section() adds a section, add_settings_field() adds a field, and settings_fields() outputs nonce fields for the form.register_setting('my_option_group', 'my_option_name');
add_settings_section('my_section', 'My Section', null, 'my_page');
add_settings_field('my_field', 'My Field', function() { echo ''; }, 'my_page', 'my_section');
// In the form:
settings_fields('my_option_group');
do_settings_sections('my_page');settings_fields('my_option_group') outputs necessary nonce and hidden fields, and do_settings_sections('my_page') outputs the registered sections and fields.register_setting('my_group', 'my_option');
add_settings_section('section_id', 'Section Title', null, 'my_page');
add_settings_field('field_id', 'Field Title', 'my_field_callback', 'my_page', 'section_id');
function my_field_callback() {
echo '';
}
// In the form:
settings_fields('wrong_group');
do_settings_sections('my_page');register_setting uses 'my_group' but settings_fields uses 'wrong_group'. They must match for nonce and saving to work.register_setting for each option before adding sections and fields.add_settings_field with correct section IDs and page slug.Pass the test and this pattern moves unknown