Using The Settings API: Part 1 - Create A Theme Options Page

If you create your own themes you will, sooner or later, want to allow your theme users have some control over certain appearance and/or functional elements of your theme. When this time comes you will want to use the powerful WordPress Settings API. With it, your code becomes simpler, more efficient and more secure.

Introduction

This tutorial is not the first to be written on using the Settings API to create a theme or plugin settings page. In fact a good number of tutorials are available in the WordPress community already. Some quality tutorials include the Extended WordPress Settings API Tutorial (in two parts) by Alison Barrett as well as the well known Incorporating the Settings API in WordPress Themes by Chip Bennett.

This tutorial builds on some excellent code techniques found in those tutorials (credit goes to both!) so if you are not familiar with them I would definitely recommend that you read those two articles too. I hope that you may find some code in this tutorial that you can use and improve on in your own work. Right then! Let's get straight to it!

A Look at What We Will Be Creating

I think it's always nice when tutorials start by showing how the finished result looks like. So why don't we start with that, shall we? For the purpose of this tutorial we will be using the twentyeleven WordPress 3.2 default theme however feel free to use your own theme if you prefer.

2. Find the Part One/source_files/lib folder and upload it inside the twentyeleven theme folder so that it is on the same level as the twentyeleven/js folder you see.
3. Then, open the Part One/source_files/functions.php in a code editor and copy the require_once code line.
4. Next, open the twentyeleven/functions.php in your code editor. Find the twentyeleven_setup() function around line 74 and paste the line you copied earlier (point 3) inside the function as you see shown below.

Upon completing this step you should be able to see the Wptuts Options link under WordPress' Appearance top-level menu of your Admin area. Go to it and take a moment to scan through the page contents. Following the Wptuts Settings Page title are four settings sections with their individual settings fields:

• Text Form Fields
• Text Area Form Fields
• Select Form Fields
• Check Box Form Fields

Note how certain settings allow HTML tags whereas other settings do not. Some settings are dedicated to numeric input only. Try saving the default settings and see the "Settings saved." admin message appear. Try saving input with HTML tags on settings that do not allow their use and see how they are cleared away. Now go to the Email Input setting and save a wrong email format like email@email. Save the setting and see the admin error message display. See also how the setting that needs to be corrected is highlighted red so that we know exactly where to go and correct things.

Now that you see what the finished result looks like, let's learn how we can re-create it step by step.

Step 1 Registering the Administration Page

"The final code described in this step is found in the Part One/source_ files/step1 folder"

This step is about creating an empty page that will eventually display our settings. As Part One of this tutorial requires only a single settings page we will simply add a submenu to the existing Appearance top level menu. (Part Two will show how to add tabs as well as more than one settings page.) We will call the add_theme_page() function within our own wptuts_add_menu()function and hook that to the admin_menu action hook.

Prepare the Document

Create a new document in your code editor and call it my-theme-settings.php Save it and upload it inside the twentyeleven/lib folder. Open the twentyeleven/functions.php in your code editor and find the require_once code line you pasted in earlier and edit the file name to reflect the name of the new document you just created.

The code given below should be written in the twentyeleven/functions.php file.

Define Our Constants

First we define some constants. This will make it a little easier when you want to customize the code to your needs later on.

All the code given below and for the remaining part of Step 1 should be written in the my-theme-settings.php file.

Register the Page

Next, tell WordPress that we want to register a settings page. For this, we need to write a function and hook it on the admin_menu action hook.

Understand the add_theme_page() parameters

Take note of the add_theme_page() function parameters so you can later on customize the function call to your needs. The information is taken from the Codex page:

• $page_title - The text to be displayed in the title tags of the page when the menu is selected • $menu_title - The text to be used for the menu
• $capability - The capability required for this menu to be displayed to the user. • $menu_slug - The slug name to refer to this menu by (should be unique for this menu). (Note the use of our WPTUTS_PAGE_BASENAME constant!)
• $function - The callback function to output the content for this page. (The wptuts_settings_page_fn() described further down.) Define a Helper Function and the Page Content Output Function The fifth parameter in add_theme_page() - i.e. wptuts_settings_page_fn() function - is responsible for displaying our page content. However, before we write it we need to define a helper function that will help bring the final page output (page title, settings sections, settings fields and contextual help) for us together. Copy and paste the code you see below after the call to the admin_menu action hook. The helper function The wptuts_get_settings() helper function outputs an associative array with the following values (in the order they are written): • The option name as we will use it in the get_option() call. (see Step 2) • The settings page title. (see below) • The settings sections. (see Step 3) • The settings fields (settings). (see Step 4) • The settings contextual help. (see Step 7) The page content output function Copy and paste the code you see below after the wptuts_get_settings() function. Check the Result If you have followed the above successfully, this is how your settings page should look like at this point. Step 2 Registering Page Settings "The final code described in this step is found in the Part One/source_ files/step2 folder" Now that we have our settings page in place we need to tell WordPress the settings we want to register and whitelist i.e. sanitize for it. This step is just about that. It will not change the appearance of our page so don't expect to actually "see" any changes reflected. All this vital work is done in the background. We will use the register_setting() function and it's sanitation callback within our custom wptuts_register_settings() function and then hook this on the admin_init action hook. Before we do this however, we need to adjust our helper wptuts_get_settings() function to include a value for $output['wptuts_option_name'].

The code given below should be written in the my-theme-settings.php file.

Register the Page Settings

Now add the next code block just below the wptuts_get_settings() function.

Understand the register_setting() parameters

Take note of the register_setting() function parameters. The information is taken from the Codex page:

• $option_group - A settings group name. (For simplicity we name it the same as the $option_name parameter below)
• $option_name - The name of an option to sanitize and save. (what we use in a get_option() call.) • $sanitize_callback - A callback function that sanitizes the option's value.

Define the Validation Callback

Finally for this step we want to define our wptuts_validate_options() validation callback function. It will not do anything yet. Nevertheless, it's good to prepare it and have it ready for Step 6. Copy and paste the code below at the end of our document and before the closing php tag.

Check the Result

If you have followed the above successfully, your settings page should still look the same as it did at the end of Step 1!

Step 3 Defining & Registering Settings Sections

"The final code described in this step is found in the Part One/source_ files/step3 folder"

This step covers the four settings sections we will need. Part of the code we'll cover will need to be written in a separate file which we will include in our my-theme-settings.php so let's start with that.

Prepare a New Document

Create a new document in your code editor and call it my-theme-options.php Copy and paste in it the function you see below. Then save the document and upload it inside the twentyeleven/lib folder.

The code given below should be written in the my-theme-options.php file.

The wptuts_options_page_sections() function defines our settings sections. It outputs an associative array. The array value stands for the section title and the array key for the section id.
Both are needed for the add_settings_section() function call later on.

Include the New Document

We want to be able to use what the wptuts_options_page_sections() function returns in the my-theme-settings.php file. Make sure to include the my-theme-options.php like you see shown below. The code is added after the call to the admin_menu action hook.

The code given below and for the remaining part of Step 3 should be written in the my-theme-settings.php file.

• $page - The settings page on which to show the section. Define the Sections Callback Function and Adjust the Page Content Output Function The settings sections callback function - i.e. wptuts_section_fn() - will echo it's contents for each section we created. Finally, we tell WordPress that we want the sections to display on our settings page. We do this by calling the 2 functions: settings_fields() and do_settings_sections() in our wptuts_settings_page_fn() Check the Result If you have followed the above successfully, this is how your settings page should look like at this point. Step 4 Defining & Registering Setting Fields "The final code described in this step is found in the Part One/source_ files/step4/ my-theme-settings.php folder" This step is all about the actual settings or as they are called in the Settings API, the settings fields. We start by defining a new helper function. Define a New Helper Function The function (written by Alison Barrett) is explained in her own tutorial so I would encourage you to read that at some point. Please take note of the fact that our wptuts_create_settings_field() function will pass the $class argument to our validation function so it is not there simply for stylistic use in a css file!

The code given below should be written in the my-theme-settings.php file just after the wptuts_get_settings() function.

Understand the add_settings_field() parameters

Take note of the add_settings_field() function parameters. The information is taken from the Codex page:

• $id - String for use in the 'id' attribute of tags. • $title - Title of the field.
• $callback - The name of the callback function that will echo the form field. • $page - The settings page on which to show the field
• $section - The section of the settings page in which to show the field • $args - Additional arguments to pass to our callback function. (These are what we mainly work with when we define our wptuts_options_page_fields() function further down)

Define the Settings Fields

The code given below should be written in the my-theme-options.php file just after the wptuts_options_page_sections() function.

Note how the arguments are used for each setting type whether it is a text input field, a textarea, a select drop down or a checkbox setting. Note the section argument and how it matches the $sections array key we output in our wptuts_options_page_sections() function. See that the class argument is regularly used for both our text and textarea settings types (this will be used in the wptuts_validate_options() function later.) Adjust the Helper Function Next, we adjust the wptuts_get_settings() helper function to include a value for the $output['wptuts_page_fields'] variable.

The code given below and for the remaining part of Step 4 should be written in the my-theme-settings.php file.

Register the Settings Fields

Let's register our settings fields by calling the wptuts_create_settings_field() helper function which ultimately calls the add_settings_field() function. Remember that just like the settings sections, the settings fields we defined are stored as an array so we need to run a foreach loop.

Define the Setting Fields Callback Function

Finally we define the wptuts_form_field_fn() callback function that will handle the form field display. Copy and paste the following code just after the wptuts_section_fn() function.

Breaking-down the code

We collect our settings fields in the $options variable. We pass the standard value ($std) if the setting is not yet set. We also put together a $field_class to be used as the form input field class (can be used for styling if needed.) Then, we run a foreach loop and switch based on the setting field type (text, textarea, select, checkbox etc.) When you customize this function later on, you will want to create a new case for each new setting field type (note: type) you add. Check the Result If you have followed the above successfully, this is how your settings page should look like at this point. Note that nothing will save yet so don't be surprised if nothing happens when you try! Step 5 Validating & Saving User Input "The final code described in this step is found in the Part One/source_ files/step5 folder" Step 5 is all about validating and sanitizing what users attempt to save when they hit the "Save Settings" button. This process, also refered to as "whitelisting" is, in my opinion, the most important part in this tutorial. If there's anything that my theme users have indelibly impressed upon me is to validate, validate, validate! So, in this tutorial we will create a project-ready validation callback function which you can use in your projects. Feel free to modify, improve and extend it according to your needs. Oh! and one more thing before we get to the actual validation function. Should you notice that your settings don't save even when everything else looks fine, this is the place to troubleshoot! So, we'll also cover a troubleshooting tip that may help. The Validation Callback Function We have already defined this function in step 2 so go ahead and find it in your my-theme-settings.php. Then copy and paste the completed function you see below in it's place. Breaking-down the code Some of the process may remind you of what we did in the setting fields callback function which handled the form field display on the page. We collect our settings fields in the $options variable.

Then, we run a foreach loop and switch based on the setting field type (text, textarea, select, checkbox etc.) When you customize this function later on, you will want to create a new case for each new setting field type (note: type) you add.

Each setting field type, the text and textarea types in particular, may be used for different user input. Sometimes the input may be some text where html elements are allowed but at other times it may be that html is not allowed, or only inline html is OK. Some settings may expect a numeric, email or url user input. All that needs to be validated properly and here is where the class argument in our wptuts_options_page_fields() function comes in.

We run a second switch based on the setting field class (nohtml, numeric, email, url etc.) which will contain different validation/sanitation code depending on what is needed. When you customize this function later on, you will want to create a new case for each new setting field class you may create. Written below, you see the class switch for the text setting field type. Take a moment to study the class switch used for the textarea setting field as well.

Take the time to study the validation/sanitation done in each case. Should you see any functions used you're not sure about, look them up. A good resource for Data Validation is found in the Codex

Troubleshooting settings that won't save

Should you notice that your settings don't save, the first thing to do is print_r both the incoming $input at the top of the validation function and the outgoing $valid_input at the end before it is returned.

If the validation code you are using is not written well then the $valid_input array values will be empty even though the $input array values look ok. Isolate the problematic settings and look into your validation code to find out what may be preventing the value of a particular $input key from being passed on as the value of the corresponding $valid_input key.

Register Errors

As you go through the validation code you will notice that what we mostly do is take the user input, "clean it up" and then pass it on to our validated input array. On occation however, such as in the case of email input, we will require the user to correct his input before saving the value in the database. We need to let the user know that there is a problem i.e. his input is not correct and that he needs to re-enter the value needed correctly. The WordPress Settings API allows us to provide such feedback using the add_settings_error() function.

You will see this function used on our text setting field type and specifically for the numeric, multinumeric and email classes. Shown below is the validation done on the email input field.

Understand the add_settings_error() parameters

Take note of the add_settings_error() function parameters. The information is taken from the Codex page:

• $setting - Slug title of the setting to which this error applies. • $code - Slug-name to identify the error. Used as part of 'id' attribute in HTML output.
• $message - The formatted message text to display to the user (will be shown inside styled <div> and <p>) • $type - The type of message it is (error or update), controls HTML class.

Check the Result

If you have followed the above successfully, then you should now be able to edit and save your settings! You will not see any admin messages (neither "success" nor "error") yet - we still have to write this (see step 6) - however your settings will be validated and saved.

"The final code described in this step is found in the Part One/source_ files/step6 folder"

In Step 5 we talked about whitelisting our settings and saving them. This is all nice however, we need to provide some sort of feedback when settings save successfully and when errors occur. Step 6 talks about displaying such feedback in the form of admin messages.

The Helper Function

WordPress provides us with an action hook we can use to echo out admin messages and this is what we will be using to display feedback both on "success" and on "error". First, we will create a helper function with 2 parameters: the actual message and the message type ("error", "info", "update", etc). I've seen this at Wp Recipes and I liked the way it was done so, we'll use it here as well.

The code given below and for the rest of Step 6 should be written in the my-theme-settings.php file just after the wptuts_validate_options() function.

The Callback Function and Action Hook

Next we need to write our callback function that will be hooked to admin_notices

Understand the function

I made sure to comment out the function well however it should be noted that the get_settings_errors() function will not only return error messages but all notices in general - including a successfull message when our settings save correctly. So don't let the function name mislead you! This is why we are able to use the same function to display the "Settings saved" admin message on "success" as well as the error messages on "error".

Check the Result

If you have followed the above successfully, then you should be able now to see the successful "Settings saved." admin message when you pass input validation, as well as the error admin message when you don't.

Error? But Where?

Now that the error message displays as expected let's add a touch of javascript to draw attention to the setting the user needs to correct. You actually have the code already uploaded on your server. You've done this already in Step 1 so all we need to do is simply include the required files in our settings page so that the browser can execute the script. Copy and paste the following above the wptuts_add_menu() function.

Then we adjust the wptuts_add_menu() function like this:

What does the js code say?

Look inside the twentyeleven/lib/js folder and open the file you see inside: wptuts_theme_settings.js in your code editor.

We look for any admin messages with the class setting-error-message. If we have any displaying on the page, we proceed and get the error message title attribute. This will always match a setting label (for attribute) and an input form field (id attribute). All is left to do, is add an error class to the label and a border style to the input form field. Note that the error class is then styled in the css file (twentyeleven/lib/css/wptuts_theme_settings.css). When you open the css file you'll see it is practically empty. Use it as you want to add further stylling to your settings page.

Check the Result (Again)

If you have followed the above successfully, then error settings should be highlighted red when error admin messages display like you see below.

"The final code described in this step is found in the Part One/source_ files/step7/ my-theme-settings.php folder"

Step 7 Contextual Help

The final Step 7 in this tutorial will touch on adding contextual help to our settings page. This additional information will be located inside the panel that slides open when you click on the "Help" tab located at the top right of your admin screen. What we need to do, is write the text we want and then tell WordPress where we want it displayed.

Write the Text

Open your my-theme-options.php file in your code editor. Copy and paste the function you see below

First we need to adjust our helper wptuts_get_settings() function to include a value for $output['wptuts_contextual_help']. The code given below and for the remaining part of Step 7 should be written in the my-theme-settings.php file. Then we adjust our wptuts_add_menu() function one last time. We call the add_contextual_help() function which takes in two parameters: $screen (our setting page) and $text (the help text we output from wptuts_options_page_contextual_help()) Check the Result If you have followed the above successfully, then our contextual help test should display inside the "Help" tab like you see below. Using the Theme Settings in Our Theme Last but not least we want to look into how we can go about using our theme settings in our theme template files. Copy and paste the following code in the twentyeleven/functions.php after the twentyeleven_setup() function. Our settings were saved in a single array with the option name wptuts_options. To retrieve them we call get_option('wptuts_options'). As you can see this is done inside our wptuts_get_global_options() fuction whose output is collected in the $wptuts_option variable.

Note: If you feel that the wptuts_get_global_options() function is somewhat redundant, don't. It's use will make more sense once you go through Part Two of this series.

Echo a particular option in any of your theme templates like this: <?php echo \$wptuts_option['wptuts_txt_input']; ?> - the value in the brackets is the id of the option you want to display.

Worth Noting

You will notice that when you try to echo the above in the header.php, sidebar.php and footer.php templates nothing happens! This is not the case in other WordPress templates (index.php, page.php etc.). Try it out for yourself to see.

Copy and paste the following in the twentyeleven/header.php after the <body> tag and see how it returns NULL on the front-end.

Now copy and paste the following just after the wp_head(); call.

Note how the variable now returns all our theme settings. Just remember this when you try to display options from your theme settings in your header.php, sidebar.php and footer.php theme templates.

Up Next... Part Two

Hope you enjoyed Part One and I look forward to reading your comments on what you thought about it. Part Two (coming tomorrow!) will show how we can create Top Level Admin menus with more than one setting pages. We will throw in some tabs too so you can see how a settings page with tabs can be created.