When should I use register_setting() and add_settings_field()
-
26-04-2021 - |
Question
When the time comes that one wants to create a settings page, one stumbles upon two semantically similar WP functions called:
I read the docs and am confused about those. Do I need both if I want to create a Settings Page in the WP Admin > Settings area?
The first one says:
"Registers a setting and its data."
But register it for what? It uses $option_group
which does not appear anywhere in the database, but seems to be used to create a nonce for a group of settings under the same hood, as I understand from this WPSE question.
It seems logic to think that it's enough to use add_settings_field()
:
"Add a new field to a section of a settings page."
But then again, what's the purpose of previously using register_setting()
?
Did I try something?
Yes, I followed multiple examples using online references, but am still confused about what each function really does.
Solution
It seems logic to think that it's enough to use
add_settings_field()
Yes, it seems so, but it's really not enough:
register_setting()
whitelists the database option for a specific setting which then allows the option to be saved and updated automatically on thewp-admin/options.php
page.Note that by "option", I'm referring to the second parameter for
register_setting()
.add_settings_field()
on the other hand "reserves a space" in a specific settings section whereby in that reserved space, you're expected to output the HTML for your settings field (which could use one or more database options).
So add_settings_field()
and register_setting()
are not interchangeable (add_settings_field()
does not automatically whitelist an option and register_setting()
does not automatically reserve the above-mentioned space), and you need to whitelist options used in your settings field or form.
For example, if it had <input name="foo_option" ...>
, then the foo_option
would need to be whitelisted like so: register_setting( 'my_settings_group', 'foo_option' )
.
And actually, the add_settings_field()
documentation emphasized that:
You MUST register any options used by this function with register_setting() or they won’t be saved and updated automatically.
And you could also see about the same warning on the Settings API handbook.. 🙂
Additional Notes
Another purpose of register_setting()
is to make a setting be available in the Site Settings (REST) API endpoint at /wp/v2/settings
, with or without actually creating any settings page.
So for example, you would do like so to make bar_option
available in the Site Settings API:
register_setting( 'some_settings_group', 'bar_option', array(
'show_in_rest' => true,
'type' => 'number',
'default' => 123,
) );