Adding Settings Fields to Your WordPress Plugin

When developing a plugin for WordPress, a lot of times you’ll want to create your own page of options within the administration area. To do so, you’ll usually use the add_options_page() or add_submenu_page() function to actually create the page; but then you’ll have to populate that page with the actual settings fields.

The first step in that process is to understand the add_settings_field() function. This function accepts 6 different parameters. They are as follows:

  1. $id – the HTML name/ID that should be passed to the callback to be used as the name/ID of the form field.
  2. $title – the text that should be used as the label for the field.
  3. $callback – the name of the function that should be used to actually build the form field. Although the label will be built automatically by WordPress, and the form field will be wrapped in a table <td> tag within the form table, you will need a callback function to actually build and echo the form field itself. The callback will receive the $id and $args parameters that are sent to the add_settings_field() function.
  4. $page – an identifier for the page on which the option field should appear.
  5. $section – an identifier for the “settings section” (add_settings_section()) in which this field should appear.
  6. $args – an array of extra arguments to pass to the function. These arguments may be helpful to you if you need to pass any additional information to the callback function, as the entire $args array will be passed as the second parameter to that callback.

    You can also use this parameter to send the ID of the form field, using the array key “label_for”. If you send an item with the array key “label_for” as part of the $args array, WordPress will automatically wrap the $title in the appropriate label tag, making your form fields more accessible. If you don’t include that array item, your titles will not be created as HTML labels. This particular functionality is not currently documented in the WordPress codex (though, I’ll probably take care of that shortly).