Using WordPress ‘add_settings_field()’ PHP function

The add_settings_field() WordPress PHP function is used to add a new field to a section of a settings page. It’s a part of the Settings API that allows you to define settings fields to appear within a section inside a settings page. The function also calls a callback function to output the HTML input tags for the setting field.

Usage

add_settings_field(
    'myprefix_setting-id', 
    'This is the setting title', 
    'myprefix_setting_callback_function', 
    'general', 
    'myprefix_settings-section-name', 
    array( 'label_for' => 'myprefix_setting-id' )
);

In this example, a new setting field is added to the ‘general’ settings page under the ‘myprefix_settings-section-name’ section.

Parameters

  • $id (string, required): Slug-name to identify the field. It is used in the ‘id’ attribute of tags.
  • $title (string, required): Formatted title of the field. This is shown as the label for the field during output.
  • $callback (callable, required): The function that fills the field with the desired form inputs. The function should echo its output.
  • $page (string, required): The slug-name of the settings page on which to show the section (general, reading, writing, etc.).
  • $section (string, optional): The slug-name of the section of the settings page in which to show the box. Default is ‘default’.
  • $args (array, optional): Extra arguments that get passed to the callback function. For example, label_for when supplied, the setting title will be wrapped in a <label> element. Its for attribute populated with this value. class is a CSS Class to be added to the <tr> element when the field is output.

More Information

See WordPress Developer Resources: add_settings_field()

Examples

Adding a Text Input Field

function text_input_callback($args) {
    $value = get_option($args['id']); 
    echo '<input type="text" id="' . $args['id'] . '" name="' . $args['id'] . '" value="' . $value . '">';
}

add_settings_field(
    'myprefix_text_input', 
    'Enter Text Here', 
    'text_input_callback', 
    'general'
);

In this example, a text input field is added to the ‘general’ settings page. The value of this field is retrieved from the WordPress database using the get_option() function.

Adding a Checkbox Field

function checkbox_callback($args) {
    $value = get_option($args['id']); 
    $checked = $value ? 'checked' : '';
    echo '<input type="checkbox" id="' . $args['id'] . '" name="' . $args['id'] . '" value="1" ' . $checked . '>';
}

add_settings_field(
    'myprefix_checkbox', 
    'Check Here', 
    'checkbox_callback', 
    'general'
);

In this example, a checkbox is added to the ‘general’ settings page. If the checkbox is checked, the value will be ‘1’. If unchecked, the value will be ‘0’.

Adding a Select Field

function select_callback($args) {
    $value = get_option($args['id']); 
    $options = ['Option 1', 'Option 2', 'Option