WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Creating Options Pages


This article is in transition to meet Settings API, which was introduced in Version 2.7. For information prior to 2.7 see this revision.

Contents

Introduction

Creating custom options panels in WordPress is relatively easy.

First, to create the menu item and the new page, see Adding Administration Menus.

So long as you stick to this structure, WordPress will handle all of the option creation, update, saving, and redirection for you. It will check permissions, and do all that other magic behind the scenes.

Several new functions were added in WordPress 2.7. These new functions are optional in WordPress 2.7 but will be required in the future. They are required for WordPress MU 2.7. See Migrating Plugins and Themes to 2.7 and Settings API for more information.

This article only covers the markup of the Settings page itself. For more information regarding how to add the Settings page, refer to Administration Menus

Where to Save the Code

You can either put the code for your options page in your plugin php file (or, for Themes, in functions.php), or you can create a second file called options.php, for example, and include it using the php include function - http://php.net/manual/en/function.include.php

Opening the Page

If you'd like to match the look and feel of existing WordPress options pages, open with the following:

<div class="wrap">
<h2>Your Plugin Page Title</h2>

Form Tag

Once you have your page, you need to create an HTML form. Use this code:

<form method="post" action="options.php"> 


settings_fields Function

The setting fields will know which settings your options page will handle.

After the opening form tag, add this function

settings_fields( 'myoption-group' );

where myoption-group is the same name used in the register_setting function.

This function replaces the nonce magic, action field, and page_options field required prior to Version 2.7.

do_settings_fields Function

After the settings_fields() call, add this function

do_settings_sections( 'myoption-group' );

This function replaces the form-field markup in the form itself.

Closing Tags

Then obviously close the form tag after your other options, and if you like, include another "Update Options" button, this is the WordPress default.

<?php submit_button(); ?>
</form>
</div>

You can personalize the button created by submit_button function.

Note the use of the _e() function to handle translation of the text, see Localizing WordPress for more info.

Register Settings

The register_setting and unregister_setting functions add and remove options from a whitelist of allowed options that the form is able to save. They can also name a sanitize callback function as a security measure to check each option's value.

The register_setting function should be called in an admin_init action, which runs before every admin page and in particular, options.php, which receives this form.

Your plugin probably has a section with an add_action that adds a new menu item to the administration menus. This line will be in the same section to add an action to admin_init.

if ( is_admin() ){ // admin actions
  add_action( 'admin_menu', 'add_mymenu' );
  add_action( 'admin_init', 'register_mysettings' );
} else {
  // non-admin enqueues, actions, and filters
}

Then you create a new function that registers each option.

function register_mysettings() { // whitelist options
  register_setting( 'myoption-group', 'new_option_name' );
  register_setting( 'myoption-group', 'some_other_option' );
  register_setting( 'myoption-group', 'option_etc' );
}

The name of myoption-group doesn't matter but it has to match the name used in the settings_fields function above.


See It All Together

Please note: Some of the code in this example (particularly do_settings) is deprecated. View Otto's tutorial here for better examples of workable code. In addition, there's another article available by ozh.

To add icon to for your options page use the following code [this will work on version 3.4.2 and later] In following example, icon is stored in "images" folder in theme directory.

<?php add_menu_page('BAW Plugin Settings', 'BAW Settings', 'administrator', __FILE__, 'baw_settings_page', get_stylesheet_directory_uri('stylesheet_directory')."/images/media-button-other.gif"); ?>

The below example uses the new Settings API to create and save your plugin options

<?php
// create custom plugin settings menu
add_action('admin_menu', 'baw_create_menu');

function baw_create_menu() {

	//create new top-level menu
	add_menu_page('BAW Plugin Settings', 'BAW Settings', 'administrator', __FILE__, 'baw_settings_page',plugins_url('/images/icon.png', __FILE__));

	//call register settings function
	add_action( 'admin_init', 'register_mysettings' );
}


function register_mysettings() {
	//register our settings
	register_setting( 'baw-settings-group', 'new_option_name' );
	register_setting( 'baw-settings-group', 'some_other_option' );
	register_setting( 'baw-settings-group', 'option_etc' );
}

function baw_settings_page() {
?>
<div class="wrap">
<h2>Your Plugin Name</h2>

<form method="post" action="options.php">
    <?php settings_fields( 'baw-settings-group' ); ?>
    <?php do_settings_sections( 'baw-settings-group' ); ?>
    <table class="form-table">
        <tr valign="top">
        <th scope="row">New Option Name</th>
        <td><input type="text" name="new_option_name" value="<?php echo esc_attr( get_option('new_option_name') ); ?>" /></td>
        </tr>
         
        <tr valign="top">
        <th scope="row">Some Other Option</th>
        <td><input type="text" name="some_other_option" value="<?php echo esc_attr( get_option('some_other_option') ); ?>" /></td>
        </tr>
        
        <tr valign="top">
        <th scope="row">Options, Etc.</th>
        <td><input type="text" name="option_etc" value="<?php echo esc_attr( get_option('option_etc') ); ?>" /></td>
        </tr>
    </table>
    
    <?php submit_button(); ?>

</form>
</div>
<?php } ?>

Example #2

This example works on WP 3.5.1. Much simpler and simply works. This is an updated version of Otto's tutorial.

<?php
class MySettingsPage
{
    /**
     * Holds the values to be used in the fields callbacks
     */
    private $options;

    /**
     * Start up
     */
    public function __construct()
    {
        add_action( 'admin_menu', array( $this, 'add_plugin_page' ) );
        add_action( 'admin_init', array( $this, 'page_init' ) );
    }

    /**
     * Add options page
     */
    public function add_plugin_page()
    {
        // This page will be under "Settings"
        add_options_page(
            'Settings Admin', 
            'My Settings', 
            'manage_options', 
            'my-setting-admin', 
            array( $this, 'create_admin_page' )
        );
    }

    /**
     * Options page callback
     */
    public function create_admin_page()
    {
        // Set class property
        $this->options = get_option( 'my_option_name' );
        ?>
        <div class="wrap">
            <?php screen_icon(); ?>
            <h2>My Settings</h2>           
            <form method="post" action="options.php">
            <?php
                // This prints out all hidden setting fields
                settings_fields( 'my_option_group' );   
                do_settings_sections( 'my-setting-admin' );
                submit_button(); 
            ?>
            </form>
        </div>
        <?php
    }

    /**
     * Register and add settings
     */
    public function page_init()
    {        
        register_setting(
            'my_option_group', // Option group
            'my_option_name', // Option name
            array( $this, 'sanitize' ) // Sanitize
        );

        add_settings_section(
            'setting_section_id', // ID
            'My Custom Settings', // Title
            array( $this, 'print_section_info' ), // Callback
            'my-setting-admin' // Page
        );  

        add_settings_field(
            'id_number', // ID
            'ID Number', // Title 
            array( $this, 'id_number_callback' ), // Callback
            'my-setting-admin', // Page
            'setting_section_id' // Section           
        );      

        add_settings_field(
            'title', 
            'Title', 
            array( $this, 'title_callback' ), 
            'my-setting-admin', 
            'setting_section_id'
        );      
    }

    /**
     * Sanitize each setting field as needed
     *
     * @param array $input Contains all settings fields as array keys
     */
    public function sanitize( $input )
    {
        $new_input = array();
        if( isset( $input['id_number'] ) )
            $new_input['id_number'] = absint( $input['id_number'] );

        if( isset( $input['title'] ) )
            $new_input['title'] = sanitize_text_field( $input['title'] );

        return $new_input;
    }

    /** 
     * Print the Section text
     */
    public function print_section_info()
    {
        print 'Enter your settings below:';
    }

    /** 
     * Get the settings option array and print one of its values
     */
    public function id_number_callback()
    {
        printf(
            '<input type="text" id="id_number" name="my_option_name[id_number]" value="%s" />',
            isset( $this->options['id_number'] ) ? esc_attr( $this->options['id_number']) : ''
        );
    }

    /** 
     * Get the settings option array and print one of its values
     */
    public function title_callback()
    {
        printf(
            '<input type="text" id="title" name="my_option_name[title]" value="%s" />',
            isset( $this->options['title'] ) ? esc_attr( $this->options['title']) : ''
        );
    }
}

if( is_admin() )
    $my_settings_page = new MySettingsPage();

This will create something like this:

File:creating-options-pages-ex-2b.png

Pitfalls

The Settings name, the second parameter in the register_setting() function, MUST match the name of the option being updated in the database!
For example, say you have add_option( 'foo_bar', 'isfoo' ), you MUST use foo_bar as the second parameter for the register_setting() function. Otherwise WordPress does not know which setting it is suppose to update and it will fail to update.

To show the menu in Multisite network screen, it would be a matter of doing:
add_action( is_multisite() ? 'network_admin_menu' : 'admin_menu', 'callback_function' );
But the form save action leads to a 404 page: /wp-admin/network/options.php.
To solve it, use the solution in this WordPress Answers post, or alternatively the one in this blog post.