How To Create A Settings Page In WordPress With The Settings Api
The Settings API is the standard way to build an options page in the admin. WordPress handles saving, security and the form submission. You only define the page, the sections and the fields.
Step 1: add the page under Settings
function lotgrafix_add_settings_page() {
add_options_page(
__( 'Lotgrafix Settings', 'lotgrafix' ),
__( 'Lotgrafix', 'lotgrafix' ),
'manage_options',
'lotgrafix-settings',
'lotgrafix_settings_page_html'
);
}
add_action( 'admin_menu', 'lotgrafix_add_settings_page' );
Step 2: register the setting, the section and the field
function lotgrafix_register_settings() {
register_setting( 'lotgrafix_group', 'lotgrafix_api_key', array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'default' => '',
) );
add_settings_section(
'lotgrafix_section_main',
__( 'Main Settings', 'lotgrafix' ),
'__return_false',
'lotgrafix-settings'
);
add_settings_field(
'lotgrafix_api_key',
__( 'API Key', 'lotgrafix' ),
'lotgrafix_api_key_field',
'lotgrafix-settings',
'lotgrafix_section_main'
);
}
add_action( 'admin_init', 'lotgrafix_register_settings' );
function lotgrafix_api_key_field() {
$value = get_option( 'lotgrafix_api_key', '' );
echo '<input type="text" class="regular-text" name="lotgrafix_api_key" value="' . esc_attr( $value ) . '">';
}
Step 3: print the page
function lotgrafix_settings_page_html() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
?>
<div class="wrap">
<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
<form action="options.php" method="post">
<?php
settings_fields( 'lotgrafix_group' );
do_settings_sections( 'lotgrafix-settings' );
submit_button();
?>
</form>
</div>
<?php
}
Read the value anywhere
$lotgrafix_key = get_option( 'lotgrafix_api_key', '' );
Other places to add the page
add_options_page(): under Settings.add_theme_page(): under Appearance.add_management_page(): under Tools.add_menu_page(): a new top level menu item, with an icon.
Notes
- The group name in
settings_fields()must match the one inregister_setting(). - The field
namemust match the option name. - For a checkbox, sanitize with a function that returns
1or0.


