When should I use register_setting() and add_settings_field()

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 the wp-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,
) );