I’ve actually used the API I’d “like” to introduce to you today several times already, but only because it was the only “right” way to do it. As a user, I like plugins that I just have to install and that then do their job in the background. Having to click through hundreds of settings spread across multiple tabs just isn’t fun. And even as a plugin developer, I try to do it that way, because in my opinion, the Settings API is one of the “ugliest” features WordPress offers. But it’s there, and it’s still the most common way to do it. So let’s take a look at it anyway.
What does the API do?
With the API, you can create settings pages for your plugins. It helps you register fields, insert them into different sections, and save or update the submitted data. It also assists you with outputting validation errors. Typically, requests are sent to options.php, where validation, automatic nonce checking, and data storage take place. When creating a settings page, there are three distinct levels:
- A “Setting” represents a stored value – usually in the
wp_optionstable – that is registered within an “Option Group” - A “Section” groups fields under a heading on the settings page
- A “Field” represents a single input field within a Section
If you also want a menu item for the settings page, strictly speaking, that’s not part of the Settings API, but rather the “Administration Menus API.” In fact, you could also add your own settings to an existing page. I’ve often done this in my plugins instead of creating another menu item. But if you absolutely want to have your own menu item, you can achieve this using the functions add_options_page() or add_menu_page().
Which functions should I know?
Probably the most important function is register_setting(), which you use to register your own setting. To attach it to a section, use add_settings_section(). Finally, you’ll need to add the field for the setting using add_settings_field().
This completes the registration process. To display the settings on a dedicated settings page, you’ll use several functions. The settings_fields() function, for example, adds the nonce field, the action, and the value for option_page to the form. With do_settings_sections(), you can insert all sections, and with submit_button(), you get the HTML markup for the button to save the settings. Using the settings_errors() function, you can display error messages previously created with add_settings_error().
What does this look like in practice?
As a small practical example, let’s expand on the code from the past two days. In the REST endpoint, we filtered by a tag, but that tag was hard-coded. If we want to make this configurable, we can build our own settings page for it – I’d probably include this on the “Reading” settings page, but I want to give you a complete example. And while we’re at it, let’s also make the length of the excerpt – which we changed yesterday using a filter – configurable.
So let’s start with the first part: registering the page, settings, sections, and fields. The code might look something like this:
function advent_calendar_add_settings_page() {
add_options_page(
__( 'Advent Calendar', 'advent-calendar' ),
__( 'Advent Calendar', 'advent-calendar' ),
'manage_options',
'advent-calendar',
'advent_calendar_render_settings_page'
);
}
add_action( 'admin_menu', 'advent_calendar_add_settings_page' );
function advent_calendar_register_settings() {
register_setting(
'advent_calendar',
'advent_calendar_settings',
[
'type' => 'object',
'sanitize_callback' => 'advent_calendar_sanitize_settings',
'default' => [
'tag' => 'wordpress-api-adventskalender',
'excerpt_length' => 30,
],
]
);
add_settings_section(
'advent_calendar_endpoint',
__( 'REST endpoint', 'advent-calendar' ),
'advent_calendar_render_endpoint_section',
'advent-calendar'
);
add_settings_field(
'advent_calendar_tag',
__( 'Tag slug', 'advent-calendar' ),
'advent_calendar_render_tag_field',
'advent-calendar',
'advent_calendar_endpoint',
[
'label_for' => 'advent_calendar_tag',
]
);
add_settings_field(
'advent_calendar_excerpt_length',
__( 'Excerpt length', 'advent-calendar' ),
'advent_calendar_render_excerpt_length_field',
'advent-calendar',
'advent_calendar_endpoint',
[
'label_for' => 'advent_calendar_excerpt_length',
]
);
}
add_action( 'admin_init', 'advent_calendar_register_settings' );
If you take a close look at the code, you’ll surely notice the various strings, which are all quite similar. It’s precisely these strings that can make your life really difficult if you make a mistake here.
The string advent-calendar here refers either to the slug of the settings page or to the text domain (which probably isn’t too surprising to you). The string advent_calendar refers to the option group, and the option name in our example is advent_calendar_settings.
Other strings, such as advent_calendar_render_settings_page, are the names of callback functions. So, are you still following along? I’ve regularly struggled to pass the correct strings or identifiers as parameters in the right places.
I won’t go into detail on most of the other things – you can look them up in the documentation if something isn’t clear.
Now that we’ve registered everything, let’s move on to the output. This is where things get “ugly,” because believe it or not: you have to write all the HTML by hand! 😱
For our simple example with the two settings fields, that would look something like this:
function advent_calendar_render_endpoint_section() {
printf(
'<p>%s</p>',
esc_html__(
'Settings for the advent calendar REST endpoint.',
'advent-calendar'
)
);
}
function advent_calendar_render_tag_field() {
$settings = get_option( 'advent_calendar_settings' );
?>
<input type="text" id="advent_calendar_tag" class="regular-text"
name="advent_calendar_settings[tag]"
value="<?php echo esc_attr( $settings['tag'] ); ?>">
<?php
}
function advent_calendar_render_excerpt_length_field() {
$settings = get_option( 'advent_calendar_settings' );
?>
<input type="number" id="advent_calendar_excerpt_length" class="small-text"
name="advent_calendar_settings[excerpt_length]" min="1" step="1"
value="<?php echo esc_attr( $settings['excerpt_length'] ); ?>">
<?php
}
function advent_calendar_render_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( 'advent_calendar' );
do_settings_sections( 'advent-calendar' );
submit_button();
?>
</form>
</div>
<?php
}
Isn’t that awful? You’d think there would be functions in the WordPress Core that output input fields or at least wrap all settings in a <form> tag with the correct action attribute, but no – none of that exists – and that’s why just about everyone ends up building their own little “API” into their plugin.
At least WordPress takes one thing off your hands. If you send data to action="options.php", WordPress automatically saves the values to the option corresponding to the field’s name. That’s why it’s recommended here to store all settings in a single large array. This also prevents you from cluttering the wp_options table with too many entries.
Here in the output, too, you’ll see the various strings mixed together again – as in settings_fields( 'advent_calendar' ) or do_settings_sections( 'advent-calendar' ) – which is why you’re well advised to avoid using the same string everywhere, if possible, to at least keep things somewhat organized.
The final part involves validating the passed-in values. We do this in the sanitize callback function. Here, we can also generate errors, which are then output as well. The code here could look like this:
function advent_calendar_sanitize_settings( $input ) {
$input = is_array( $input ) ? $input : [];
$tag = sanitize_title( $input['tag'] ?? '' );
$excerpt_length = absint( $input['excerpt_length'] ?? 0 );
if ( '' === $tag ) {
add_settings_error(
'advent_calendar_settings',
'advent_calendar_empty_tag',
__( 'The tag slug must not be empty.', 'advent-calendar' )
);
$tag = 'wordpress-api-adventskalender';
}
return [
'tag' => $tag,
'excerpt_length' => $excerpt_length > 0 ? $excerpt_length : 30,
];
}
It’s important here that you always return a complete array and not just a single value that you’re checking. And don’t just return $input, because otherwise, external keys might end up in your database option.
If a value is invalid, you’ll need to decide how to handle it. For example, you could return a default value or use get_option() to retrieve the currently stored value and use that instead.
When it comes to the length of the excerpt, we’re keeping it simple. With absint(), we always get a positive number or 0. If the result here is 0 – for example, because the field was empty – we’ll use the default value of 30 words again. The min attribute in the numeric field helps in the browser, but it doesn’t replace the validation on the server. You must always perform this validation when saving data from the browser.
Let’s quickly take a look at how we can incorporate this into our REST endpoint from Day 1. Here, we simply read the values from the option and use them instead of the static values:
function advent_calendar_get_post( WP_REST_Request $request ) {
$post = get_post( $request->get_param( 'id' ) );
$settings = wp_parse_args(
get_option( 'advent_calendar_settings', [] ),
[
'tag' => 'wordpress-api-adventskalender',
'excerpt_length' => 30,
]
);
$is_visible = $post
&& 'post' === $post->post_type
&& is_post_publicly_viewable( $post )
&& ! post_password_required( $post )
&& has_tag( $settings['tag'], $post );
// ...
$excerpt_length = (int) apply_filters(
'advent_calendar_excerpt_length',
$settings['excerpt_length'],
$post
);
// ...
}
We’re supplementing the default values here with wp_parse_args(). Since we’re only registering the setting in admin_init, the default value from register_setting() doesn’t take effect during a REST request. Without the default values, we’d be working with an empty array until someone saves the settings page.
For the excerpt length, the saved value replaces yesterday’s fixed value of 30. However, we’re keeping the filter. This way, you can set the default on the settings page but still adjust it for individual posts using the filter.
What should I watch out for?
As mentioned several times already, you must be very careful not to mix up the strings or identifiers. In particular, the option group string must match in register_setting() and settings_fields(), and the page slug must match in add_settings_section(), add_settings_field(), and do_settings_sections(). If something is incorrect here, fields won’t be displayed, values won’t be saved, and so on.
If you use a “checkbox” in a field, be aware that this field will not appear in the request if it is not checked. This is standard behavior in HTML. For a single option, your sanitize callback will receive null; for an array, the corresponding key will be missing. You must treat both cases as “unchecked” yourself.
Your sanitize callback is also executed with every update_option() call in your request, not just when saving; and if the option doesn’t exist yet, the callback function is executed twice – in update_option() and add_option(). So write the function in such a way that, for example, an error message isn’t generated twice.
Of course, it’s very important that you validate and sanitize all submitted values and also escape them in the output within your custom HTML. Unfortunately, the Settings API doesn’t handle this entirely for you.
You should register all your fields within the admin_init action so that this happens only in the backend – not, for example, in plugins_loaded or similar actions. However, this means that the sanitize callback and the default value will also be available only in the backend, as we just saw with the REST endpoint.
Settings can generally only be viewed and modified with the manage_options permission, and using the method shown here, only for a single site or a single site within a multisite network. If you’d like to use different permissions or create settings pages for the entire multisite network, it’s best to check the documentation to see how to do that. That would go a bit beyond the scope of this blog post.
When should I use it?
If you need a lot of settings for your plugin, then a settings page can definitely make sense. If you only have a few things that need to be configurable, you might simply add your settings to an existing WordPress settings page (e.g., “Reading” or “Discussion”).
The big advantage of the Settings API is that many tasks – such as nonce validation, permission checks, and saving – happen automatically.
Settings pages built using WordPress’s JavaScript packages have emerged as a “modern alternative.” There isn’t an official standard for this yet, but some plugins use settings pages built using the various @wordpress/components and then use the /wp/v2/settings REST endpoint to save settings. To do this, you need to register the settings with show_in_rest in such a way that they’re also registered for REST requests – for example, in init instead of admin_init. I haven’t implemented this approach myself yet, but I think it will completely replace the Settings API in the not-too-distant future.
Where can I find more information?
- Plugin Handbook: Settings
- Custom Settings Page
- Options API
- Settings API
- Using the Settings API
- Plugin Handbook: Administration Menus
- Code Reference:
register_setting() - Code Reference:
add_settings_section() - Code Reference:
add_settings_field() - Code Reference:
settings_fields() - Code Reference:
do_settings_sections() - Code Reference:
add_settings_error()
What should I remember?
- The Settings API handles tasks such as form processing, nonce verification, and permission checks for you, and saves your registered settings as options.
- Make sure to use the correct strings/identifiers for the option group, page slug, and option name; otherwise, your settings page won’t work.
- The sanitize callback validates your values, but you’ll need to handle missing values – such as those from checkboxes – yourself and always return all values.
I’m curious to hear what you think about the Settings API. Have you used it yourself yet? Was it just as frustrating for you as it was for me? Or did you move your settings pages to React a long time ago?