Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 68 ยท Shortcodes, Options and Admin Pages

The Settings API

Build safe plugin settings pages with the WordPress Settings API: register_setting, sections, fields, sanitize callbacks, defaults, error messages and REST.

You could build a settings page by hand: a form, a handler that reads $_POST, a call to update_option(). Many old plugins did exactly that, and many of them had security holes, because every author had to remember the nonce, the capability check, the sanitizing and the redirect. The Settings API is WordPress's answer. You describe your settings (name, section, field, how to clean the value) and WordPress handles the form submission, the permission check, the nonce and the saving.

This lesson explains the pieces and how they fit together. The API runs in the admin area, so the real WordPress code below is read-only. A runnable stand-in at the end shows how a registered setting turns a submission into either saved, cleaned values or error messages. Settings are stored with the Options API from The Options API and Transients, so make sure that lesson makes sense first.

The big picture

The Settings API has three layers, and each is registered on the admin_init hook:

  1. Settings: register_setting() ties an option name to an option group and says how to sanitize it.
  2. Sections and fields: add_settings_section() and add_settings_field() describe what appears on the page.
  3. The page: your menu page callback prints a <form> that posts to options.php, which saves everything for you.
sequenceDiagram
    participant B as Browser
    participant P as Your settings page
    participant O as wp-admin/options.php
    participant S as sanitize_callback
    participant D as wp_options
    B->>P: Open settings page
    P-->>B: Form (nonce, option_page, fields)
    B->>O: POST form
    O->>O: Check nonce and capability
    O->>S: Value for each registered setting
    S-->>O: Cleaned value (or error message)
    O->>D: update_option()
    O-->>B: Redirect back with settings-updated

The form posts to options.php, which verifies the request, runs your sanitize callback and saves the option.

The menu page itself is covered in Admin Pages, Menus and List Tables. Here we focus on what goes inside it.

Registering a setting

PHP
add_action( 'admin_init', 'nw_register_settings' );

function nw_register_settings() {
	register_setting(
		'nw_options_group',   // option group
		'nw_greeting',        // option name (the row in wp_options)
		array(
			'type'              => 'string',
			'description'       => 'Text shown at the top of the site.',
			'sanitize_callback' => 'sanitize_text_field',
			'default'           => 'Welcome',
			'show_in_rest'      => true,
		)
	);
}

What each part does:

  • Option group: a label that connects the form to the settings it may save. The form prints this name in a hidden field, and options.php only saves options registered under that group. This is a safety feature: a crafted request cannot write arbitrary options through your form.
  • Option name: the key used with get_option() and update_option(). Use a prefix.
  • type: one of string, boolean, integer, number, array or object. It documents the value and is used by the REST API.
  • sanitize_callback: a function that receives the submitted value and returns the value to store. This is where you clean input. For a text field sanitize_text_field is often enough; for anything stricter write your own function.
  • default: the value get_option() returns when the option has not been saved yet and you did not pass a default yourself.
  • show_in_rest: expose the setting through the REST API at /wp-json/wp/v2/settings, where users who can manage options can read and write it. Leave it off for secrets such as API keys.

Sections and fields

A section is a heading with an optional description. A field is one input inside a section.

PHP
add_action( 'admin_init', 'nw_register_fields' );

function nw_register_fields() {
	add_settings_section(
		'nw_main_section',          // section id
		'Greeting',                 // title
		'nw_main_section_intro',    // callback that prints the description
		'nw-settings'               // page slug
	);

	add_settings_field(
		'nw_greeting_field',        // field id
		'Greeting text',            // label
		'nw_greeting_field_html',   // callback that prints the input
		'nw-settings',              // page slug (must match the section)
		'nw_main_section',          // section id
		array( 'label_for' => 'nw_greeting' )
	);
}

function nw_main_section_intro() {
	echo '<p>Shown at the top of every page.</p>';
}

function nw_greeting_field_html() {
	printf(
		'<input type="text" id="nw_greeting" name="nw_greeting" value="%s" class="regular-text">',
		esc_attr( get_option( 'nw_greeting' ) )
	);
}

Two names are easy to confuse. The page slug (nw-settings) groups sections and fields for do_settings_sections(). The option group (nw_options_group) groups settings for settings_fields(). They are different strings and may differ.

The field callback must print the input itself, and the name attribute must equal the option name. Always escape the stored value when you print it back (esc_attr() for attribute values), as you will see in Escaping Output.

The page and the form

The menu page callback prints the form. The three helper calls inside it do the heavy lifting:

PHP
function nw_settings_page() {
	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( 'nw_options_group' );
			do_settings_sections( 'nw-settings' );
			submit_button( 'Save settings' );
			?>
		</form>
	</div>
	<?php
}
  • settings_fields( 'nw_options_group' ) prints hidden inputs: the nonce, the option_page value and action=update.
  • do_settings_sections( 'nw-settings' ) prints every section registered for that page and the fields inside them, laid out as a table.
  • submit_button() prints the styled save button.

The form posts to options.php. That file checks the nonce, checks the user's capability (by default manage_options), runs each sanitize callback and saves the options. Afterwards it redirects back to the page you came from.

If your page sits under Settings in the menu, WordPress also prints the result messages ("Settings saved.") for you. For a page under a custom top-level menu, call settings_errors() at the top of your callback to show them.

Sanitizing and reporting problems

The sanitize callback is your only chance to reject or clean a value. It always returns the value to store. When the input is invalid, call add_settings_error() and return the old value so the bad input is not saved:

PHP
function nw_sanitize_per_page( $value ) {
	$value = absint( $value );

	if ( $value < 1 || $value > 50 ) {
		add_settings_error(
			'nw_per_page',          // setting name
			'nw_per_page_range',    // error code
			'Posts per page must be between 1 and 50.',
			'error'                 // 'error' or 'success'/'updated'
		);
		return get_option( 'nw_per_page', 10 );
	}

	return $value;
}

settings_errors() prints the collected messages as dismissible admin notices. Remember that a sanitize callback can run more than once for the same save in some situations, so it should have no side effects other than adding messages.

For an array option (several values in one row), the callback receives the whole submitted array and should build a new array containing only the keys it knows, each cleaned on its own:

PHP
function nw_sanitize_settings( $input ) {
	$clean = array();
	$clean['color']    = in_array( $input['color'] ?? '', array( 'blue', 'green' ), true )
		? $input['color']
		: 'blue';
	$clean['per_page'] = absint( $input['per_page'] ?? 10 );
	return $clean;
}

Using an allow-list for choice fields is stronger than trying to remove bad characters. More on cleaning input in Sanitizing and Validating Input.

The stand-in: a settings form renderer

The Settings API cannot run here, so the TryIt below is a small plain-PHP model with the same ideas: a registry with settings, sections and fields; a renderer that prints a form with an option group and escaped values; and a save step that runs each setting's sanitize callback, keeps the old value after an error and reports messages. The function names are ours, not WordPress's.

PHP A settings registry with sanitize callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Watch three things in the output. The tags are stripped from the greeting, so it is stored as the plain text alert(1)Hello (the code is no longer wrapped in a script tag, though its text remains). The invalid page count produces a message and the previous value (the default 10) survives. And nw_secret_flag was never registered, so it is ignored: this is the same protection the option group gives the real API.

Common mistakes

  • Mismatched names. The input's name must equal the registered option name, and the page slug in add_settings_field() must equal the one in do_settings_sections(). A typo gives you a field that looks fine but never saves.
  • Forgetting settings_fields(). Without it options.php refuses the post.
  • Registering outside admin_init. Register settings, sections and fields on admin_init.
  • Unsanitized arrays. If a sanitize callback returns $input untouched, nothing is protected.
  • Exposing secrets in REST. Do not set show_in_rest for tokens and passwords.
  • Using it for non-admin forms. The Settings API is for administrators editing options. Front-end forms use a different pattern: see Forms and Nonces.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the form built for the Settings API post to?

    The form's action is options.php in wp-admin, which verifies the nonce and capability, runs the sanitize callbacks and saves the options.
  2. 2. What is the job of settings_fields( 'my_group' )?

    settings_fields() outputs hidden inputs including the nonce and option_page. Visible fields come from do_settings_sections().
  3. 3. A sanitize callback finds the submitted value invalid. What is the recommended handling?

    Return the old value so bad input is not stored, and report the problem with add_settings_error(); settings_errors() shows it to the user.
  4. 4. Why is show_in_rest unsuitable for an API secret?

    show_in_rest publishes the setting through the REST settings endpoint. It is limited to users who can manage options, but a secret does not need that extra exposure.

Summary

  • The Settings API handles nonce, capability, sanitizing and saving for admin option forms.
  • register_setting() connects an option to a group and a sanitize_callback; add_settings_section() and add_settings_field() describe the page; all are registered on admin_init.
  • The form posts to options.php and starts with settings_fields(); do_settings_sections() prints the fields.
  • Sanitize callbacks return the value to store; on invalid input call add_settings_error() and return the old value.
  • default supplies a fallback for get_option(), and show_in_rest exposes the setting at /wp/v2/settings.
  • Only options registered in the submitted group are saved.

Next: Admin Pages, Menus and List Tables.