The do_settings_fields() WordPress PHP function is part of the Settings API. It is used to output a specific settings section on a settings page.
Usage
To use do_settings_fields(), you need to provide two parameters:
do_settings_fields($page, $section);
Here, $page
is the slug title of the admin page whose settings fields you want to show, and $section
is the slug title of the settings section whose fields you want to show.
Parameters
- $page (string) – Required. This is the slug title of the admin page whose settings fields you want to show.
- $section (string) – Required. This is the slug title of the settings section whose fields you want to show.
More information
See WordPress Developer Resources: do_settings_fields()
This function is part of WordPress’s Settings API.
Examples
Displaying Settings for a Custom Page
This example shows how to use do_settings_fields() to display the settings fields for a custom admin page. We’ll assume that we have a settings page with the slug ‘my-custom-page’ and a settings section with the slug ‘my-section’.
settings_fields('my_custom_settings'); echo '<table class="form-table">'; do_settings_fields('my-custom-page', 'my-section'); echo '</table>';
Displaying Settings for Different Sections
In this example, we show how to display settings for different sections based on a GET parameter. This could be useful if you have different settings sections for different functionalities of your plugin or theme.
if ($_GET['type'] !== 'advanced') { settings_fields('my_basic_settings'); echo '<table class="form-table">'; do_settings_fields('my-custom-page', 'basic-section'); echo '</table>'; } else { settings_fields('my_advanced_settings'); echo '<table class="form-table">'; do_settings_fields('my-custom-page', 'advanced-section'); echo '</table>'; }
Displaying Multiple Settings Sections
If you have multiple settings sections on a single settings page, you can call do_settings_fields() multiple times to display them all.
settings_fields('my_settings'); echo '<table class="form-table">'; do_settings_fields('my-custom-page', 'section-1'); do_settings_fields('my-custom-page', 'section-2'); do_settings_fields('my-custom-page', 'section-3'); echo '</table>';
Conditional Display of Settings Sections
You can use do_settings_fields() in combination with conditions to control which settings sections are displayed.
settings_fields('my_settings'); echo '<table class="form-table">'; if ($some_condition) { do_settings_fields('my-custom-page', 'section-1'); } else { do_settings_fields('my-custom-page', 'section-2'); } echo '</table>';
Displaying Settings for Custom Post Types
Here, we display settings fields for a custom post type settings page. We’re assuming a custom post type with the slug ‘my-custom-post-type’ and a settings section with the slug ‘cpt-section’.
settings_fields('my_cpt_settings'); echo '<table class="form-table">'; do_settings_fields('my-custom-post-type', 'cpt-section'); echo '</table>';