WordPress Settings Form Helper

I am currently writing my first WordPress plugin. I attempted to use the Settings API on my plugin’s settings page, but found it was a little cumbersome. So I wrote a helper to cut down the number of functions I needed to define. My plan was originally to simply automate the API calls, but it quickly outgrew the Settings API and does quite a bit more. I am posting it, hoping that it will be of use to some other plugin developers. The class handles form creation, display of options, security (wpnonce, back-end validation), and storage.

Operation

The class stores plugin options in a serialized array in the ‘wp_options” table (the recommended approach). On admin_init, the developer instantiates the class, passing a configuration array, and calls $instance->register(). The configuration array contains the name of the option for storage, and a description of the form. When creating the page for the form, the developer calls $instance->echo_settings_page().

Simple mode

In simple mode, the class stores a flat array of name=>value pairs. It will not disturb other options stored in the same array (so you can have some options exposed by the settings form and others that only your plugin accesses).

Multi mode

In multi mode, the class stores an array of arrays. This would be useful if your plugin stores lists that are too complex for a textarea, but too short or infrequently accessed to justify creating a database table. The echo_settings_page() function takes care of displaying a table containing the list, as well as displaying forms to insert new rows and edit existing ones. Checkboxes next to the list can be used to delete or run custom functions on selected rows.

Example usage

The following code would create the “Simple Settings Form” in the image above.


$form = new WP_Settings_Form(array(
 "option_name" => "wpdemo_simple",
 "sections" => array(
  array(
   "title" => "Simple Settings Form",
   "fields" => array(
    array(
     "name" => "title",
     "label" => "Title",
     "type" => "text",
     "size" => 60
    ),
    array(
     "name" => "tags",
     "label" => "Tags",
     "description" => "Comma-separated list of tags",
     "type" => "text",
     "validator" => array(
      "type" => "preg_replace",
      "pattern" =>"|[^a-zA-Z0-9, _-]|",
      "replacement" => ""
     )
    ),
    array(
     "name" => "categories",
     "label" => "Categories",
     "type" => "categories",
     "validator" => array(
      "type" => "numeric"
     )
    ),
    array(
     "name" => "author",
     "label" => "Author",
     "type" => "authors",
     "validator" => array(
      "type" => "numeric"
     )
    )
   )
  )
 )
));
$form->register();
...
$form->echo_settings_page();

Download

I have prepared a demo plugin implementing both the simple and multi modes of the class.

Related Post

Read More
Read More
Read More
Read More