Try Tuts+ Premium, Get Cash Back!
The Complete Guide To The WordPress Settings API, Part 8: Validation, Sanitisation, and Input II

The Complete Guide To The WordPress Settings API, Part 8: Validation, Sanitisation, and Input II

Tutorial Details
  • Program: WordPress
  • Version: 3.0+
  • Difficulty: Intermediate
  • Estimated Completion Time:Varies
This entry is part 8 of 8 in the series The Complete Guide To The WordPress Settings API

We’ve reached the final article of the series. In the last post, we took a look at introducing validation, sanitization, and a couple of basic input elements that we can take advantage of when building option pages.

In this article, we’re going to take a look at the final set of three options and how to hook them up to the front-end of the theme.

Before we get started: As with the last few, this article assumes that you’ve been following along with the rest of the series, have a working copy of the sample code installed, and are now relatively familiar with the Settings API and theme options. If you’re uncertain about any of the above, I highly recommend reading the rest of the articles before diving into this post.


The Element Types, Continued

Checkbox

Earlier in this series, we added checkboxes. We could go back and revisit those, but let’s keep consistent with what we’ve done up to this point and introduce new options. Once we’re done, you can revisit the code we added at the beginning of the series for review.

First, let’s introduce the checkbox element to the sandbox_theme_initialize_input_examples function:

add_settings_field(
	'Checkbox Element',
	'Checkbox Element',
	'sandbox_checkbox_element_callback',
	'sandbox_theme_input_examples',
	'input_examples_section'
);

Next, we need to go ahead and define the callback that we’ve specified above. Add the following function to your project:

function sandbox_checkbox_element_callback() {

	$options = get_option( 'sandbox_theme_input_examples' );
	
	$html = '<input type="checkbox" id="checkbox_example" name="sandbox_theme_input_examples[checkbox_example]" />';
	$html .= '<label for="checkbox_example">This is an example of a checkbox</label>';
	
	echo $html;

} // end sandbox_checkbox_element_callback

We’ll be revisiting this function momentarily, but first notice that I’ve added a label element next to the checkbox. Checkboxes often have an element associated with them that also afford the ability to be clicked to trigger the checkbox. This makes it easier for users to toggle an option without having to click precisely in the checkbox.

To associate a label with a checkbox, you need to give the label’s for attribute the value of the ID attribute of the checkbox to which it is bound. Easy enough, right?

Now, refresh your options page and you should see the new element visible on your options page. But, for now, it doesn’t actually save or retrieve a value. First, let’s introduce a value attribute on the checkbox. This is somewhat arbitrary but it’s a common practice to give a checked element a value of ’1.’ Let’s do that now:

$html = '<input type="checkbox" id="checkbox_example" name="sandbox_theme_input_examples[checkbox_example]" value="1" />';

Next, let’s think through exactly what needs to happen when we save a value. Ideally:

  • The user checks the element and saves the value
  • The page refreshes and the checkbox is checked
  • The user checks the element to disable it and saves the value
  • The page refreshes and the checkbox is not checked

Relatively clear, right? Rather than reading the option, setting up a conditional, and checking for the presence or absence of a value, we can take advantage of WordPress’ checked function.

The function accepts three arguments, only the first of which is required:

  1. The first value is one of the values to compare
  2. The second value to compare if the first value is not true
  3. Whether or not to echo check="checked" to the browser

So let’s update our code to use this function:

$html = '<input type="checkbox" id="checkbox_example" name="sandbox_theme_input_examples[checkbox_example]" value="1"' . checked( 1, $options['checkbox_example'], false ) . '/>';

Refresh the page and check the option, save, and repeat.

If any of this looks a bit confusing, review the previous article where we cover the significances of each attribute on an option element.

Finally, let’s update the front end of the theme to check this option and render a string of text based on if the option has been checked. Recall that when we created the element, we gave it the value of ‘1‘. This means that when the checkbox is checked and serialized, it will maintain a value of one. Simply put, we need to write a conditional that checks the value of the option and then renders text appropriately. In index.php, add this block of code:

<?php if( $input_examples['checkbox_example'] == '1' ) { ?>
	<p>The checkbox has been checked.</p>
<?php } else { ?>
	<p>The checkbox has not been checked.</p>
<?php } // end if ?>

Now, go back to your settings page, toggle the checkbox, and refresh your page.

As mentioned at the beginning of this section, look back at the ‘Display Options’ that we introduced earlier in this series and see if it’s much clearer now that we’ve examined how to introduce and manage checkbox elements.

Radio Buttons

Radio Buttons are elements that are useful in groups – after all, you’re never going to use a single radio button. The thing about radio elements is that they provide a way to allow users to choose one out of a mutually exclusive set of options.

For one reason or another, radio buttons are often a challenge for WordPress developers. Hopefully, we’ll make it as easy as possible to bring into our projects. As with the rest of the examples in this series, detail what we’re going to do:

  • We want to introduce two options from which the user must select. We’ll be giving them very general labels.
  • The first option will be a radio element with the label ‘Option One’ and will have the value of ’1′.
  • The second option will be a radio element with the label ‘Option Two’ and will have the value of ’2′.

Seems clear enough – let’s go ahead and add the field element to our options page:

add_settings_field(
	'Radio Button Elements',
	'Radio Button Elements',
	'sandbox_radio_element_callback',
	'sandbox_theme_input_examples',
	'input_examples_section'
);

And let’s implement the radio element’s callback. First, we’ll specify the code, then we’ll review it:

function sandbox_radio_element_callback() {

	$options = get_option( 'sandbox_theme_input_examples' );
	
	$html = '<input type="radio" id="radio_example_one" name="sandbox_theme_input_examples[radio_example]" value="1"' . checked( 1, $options['radio_example'], false ) . '/>';
	$html .= '<label for="radio_example_one">Option One</label>';
	
	$html .= '<input type="radio" id="radio_example_two" name="sandbox_theme_input_examples[radio_example]" value="2"' . checked( 2, $options['radio_example'], false ) . '/>';
	$html .= '<label for="radio_example_two">Option Two</label>';
	
	echo $html;

} // end sandbox_radio_element_callback

The first thing to notice when working with radio buttons is that they do not follow the typical examples of how to set the ID and name attributes. Notice that the ID attribute is unique and has no relationship to the rest of the attributes on the element. Also notice that each element’s associated label uses the ID for it’s for attribute. This binds the label to the radio button so that users can click on the label to select the radio element.

Next, notice that the name attributes are the same for each radio element but the values are different. This is what makes radio buttons mutually exclusive – each radio element needs to have the same name but the values must be unique.

Finally, we can set up a conditional on the homepage by checking the element’s value. In your theme’s functions.php, add the following block of code:

<?php if( $input_examples['radio_example'] == 1 ) { ?>
	<p>The first option was selected.</p>
<?php } elseif( $input_examples['radio_example'] == 2 ) { ?>
	<p>The second option was selected.</p>
<?php } // end if  ?>

Load your theme’s homepage, toggle the options, and refresh. You should see the two sentences changing based on the value of the option elements.

Select Box

The last element that we’re going to review is the select element. This element gives users a drop-down menu of options from which to choose. Let’s plan out exactly what we need to introduce for this element:

  • Define a select element. In our example, we’ll be treating it as three options for time.
  • We’ll give the options for ‘Never’, ‘Sometimes’, and ‘Always’.
  • We’ll populate a default option that will be set when the page loads.

At this point in the series, this should be quite routine. Let’s get started – first, we’ll introduce the settings field:

add_settings_field(
	'Select Element',
	'Select Element',
	'sandbox_select_element_callback',
	'sandbox_theme_input_examples',
	'input_examples_section'
);

Next, we’ll define the callback function. Review the code and then we’ll discuss it after the example:

function sandbox_select_element_callback() {

	$options = get_option( 'sandbox_theme_input_examples' );
	
	$html = '<select id="time_options" name="sandbox_theme_input_examples[time_options]">';
		$html .= '<option value="default">Select a time option...</option>';
		$html .= '<option value="never"' . selected( $options['time_options'], 'never', false) . '>Never</option>';
		$html .= '<option value="sometimes"' . selected( $options['time_options'], 'sometimes', false) . '>Sometimes</option>';
		$html .= '<option value="always"' . selected( $options['time_options'], 'always', false) . '>Always</option>';
	$html .= '</select>';
	
	echo $html;

} // end sandbox_radio_element_callback

First, refresh your options page to make sure the select element appears. Assuming that it does, let’s review the code above.

When defining the select element, we’ve given it an ID attribute and a name attribute much as we do with the rest of the elements that we’ve demonstrated. Next, each option has a unique value and text that corresponds to the value. Though you don’t have to do this, I’ve typically found it helpful when working in my projects. Finally, we’ve taken advantage of the selected helper that WordPress offers. This is much like the checked function that we’ve used in previous example except that it’s geared towards select options.

The last step will be to update the front end of the theme so that it checks the value of the select element after it has been saved. Add the following block of code to your index.php:

<?php if( $input_examples['time_options'] == 'never' ) { ?>
	<p>Never display this. Somewhat ironic to even show this.</p>
<?php } elseif( $input_examples['time_options'] == 'sometimes' ) { ?>
	<p>Sometimes display this.</p>
<?php } elseif( $input_examples['time_options'] == 'always' ) { ?>
	<p>Always display this.</p>
<?php } // end if/else ?>

Revisit the homepage of your theme, change up the options, and then refresh the page – you should notice the text update based on the option that you’ve selected.


Conclusion

With that, we finally reach the end of this series. The Settings API is a powerful feature of WordPress and provides us with the ability to implement well-designed, secure option pages, but it requires that we use it properly. Unfortunately, this is probably one of the most ignored features of the platform by many developers.

Ultimately, my goal was to walk developers through the API from the very beginning of understanding why it’s important, to settings, from menu pages, to tabbed navigation, and how to work with each of the element types.

Finally, remember that you can find the example code on GitHub. As you continue to work with the Settings API or find a feature that’s unclear, please contribute. I’d love for this series and the example code to continue to provide a source of education for the WordPress community.


Related Sources


Other parts in this series:The Complete Guide To The WordPress Settings API, Part 7: Validation, Sanitisation, and Input I
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://daankortenbach.nl Daan Kortenbach WordPress Expert

    Thank you for this amazing series of incredible in depth knowlegde. A must for every WordPress developer, even for seasoned developers.

    • http://tommcfarlin Tom McFarlin
      Author

      Thank you!

  • Pingback: The Complete Guide To The WordPress Settings API, Part 8: Validation, Sanitisation, and Input II | Qtiva

  • Andrew

    Great series, thanks for sharing it with us.

    • http://tommcfarlin.com Tom McFarlin
      Author

      Sure thing, Andrew!

  • http://www.creativesnails.com/ bobural

    I can not emphasize how much I appreciate these tutorials…

    Thank you!!!!

    • http://tommcfarlin.com Tom McFarlin
      Author

      Glad to hear it, Bobural!

  • http://www.wpfix.org Wpfix

    Awesome series of tuts

    :)

    • http://tommcfarlin.com Tom McFarlin
      Author

      Thanks!

  • supprof1

    video tutorial please

    • http://tommcfarlin.com Tom McFarlin
      Author

      No video tutorials for this – but be sure to check out the source code for the entire series here.

  • Andrew

    Awesome stuff thanks, just finished. Time to go put it to good use. Can you or anyone else recommend any resources for handling image uploads and other trickier situations?

    • http://tommcfarlin.com Tom McFarlin
      Author

      Hey Andrew,

      Thanks for the comments!

      I’ve received quite a few emails about how to manage file uploads in the WordPress admin. Perhaps I’ll do a series on this in the coming months.

  • Pingback: WordPress Weekly Links: May 7, 2012 - May 14, 2012 | WPStream.com

  • Luis

    This is the best tutorial I’ve read about the WordPress settings API. I am really thankful for this and ready to start practicing! :)

    • http://tommcfarlin.com Tom McFarlin
      Author

      Thanks Luis – good luck!

  • Salman

    This was a great series of WP Tuts. I’ve learned new and awesome thing from this series. Thank you.

    • http://tommcfarlin.com Tom McFarlin
      Author

      Glad to hear it, Salman!

  • general

    Thanks for the great series!
    It’s clear you have put in a great amount of effort to create these tutorials.
    If I happen to make a decent theme, and it sells well, you could say these tutorials were life-changing ;)

    • http://tom@tommcfarlin.com Tom McFarlin
      Author

      Love hearing that!

  • http://wpconsult.net Paul

    thanks Tom, I’m using what I learnt from the series to add a settings page to a plugin I’m developing!

    • http://tommcfarlin.com Tom McFarlin
      Author

      Love it – good luck!

  • http://furiousballmedia.com furiousBall

    Thanks for the tutorial, Tom. Fantastic job! I am also going to be using what I learned to build a plug-in for a new WP project. You rock socks!

    • http://tommcfarlin.com Tom McFarlin
      Author

      Thank you sir!

  • Dan

    You should put the entire series into an ebook.
    I’d even be willing to pay for it :)

    Dan

    • http://tommcfarlin.com Tom McFarlin
      Author

      Dan – thanks! I’ve actually been considering doing this as well as revising some of the articles and improving some of the code samples.

      We’ll see!

  • http://fronterahouse.com/ Mike

    Great article! Do you by chance have an example of how to do a file upload type (e.g. for uploading a custom logo to your branding)? I’m having trouble trying to figure out how to properly declare the type, have it store the value, and validate it properly.

    • http://fronterahouse.com/ Mike

      I found an article from Otto that I’m attempting to merge with my settings scripts to handle a file upload. I’ll post back here if I can figure out how to get it working.

    • Tom McFarlin
      Author

      For the Settings API, I don’t although this could be a good topic for a future article. I’ll make a note and see what I can do!

  • Pingback: Best of Tuts+ in May 2012 - Milk-Break

  • Pingback: Best of Tuts+ in May 2012 « Webby Treats

  • Pingback: Best of Tuts+ in May 2012 | Shadowtek Hosting and Design Solutions

  • Pingback: My Stream | Best of Tuts+ in May 2012 | My Stream

  • http://www.DesignLoud.com Derek

    Great tut Tom! I have a quick question on something I dont see visited here.. How would I go about adding the hex color picker as an option? I am trying to have it where someone will pick a background color for example the header area and I want to give this option through the options panel you have walked us through here.. I see it done on numerous other themes and I thought you may have an ‘easy’ solution for this, without me having to dig through other themes codes to see exactly how they did it..

    But thanks for the awesome read!

    • http://www.greenleaf-net-solutions.com/ Colin Crawford

      Hi Derek, I would like to do the same for a website but struggling to find the right information. The Twenty Eleven theme uses an option to change the header text colour, so maybe see how that is done.

      I’ve looked at the theme-options page and got a bit lost, I’ve only looked into this today and felt Tom holding my hand through his tutorials and looking through this file is a bit daunting. Maybe Tom or someone could write a tutorial or point us in the right direction.

      Tom, hint hint

      by the way Derek have you found out how to do it since posting here?

    • Tom McFarlin
      Author

      Hey Derek,

      This is another one of the advanced topics. I’m collecting these and will see what I can do in future articles to help you guys out.

      Can’t promise any particular release dates but I’ll publish something as soon as I can get to it :).

  • Pingback: Best of Tuts+ in May 2012 | DigitalMofo

  • Pingback: Best of Tuts+ in May 2012 | Gallery.Clipapic

  • Pingback: Best of Tuts+ in May 2012 | clickshots

  • Pingback: Best of Tuts+ in May 2012

  • Pingback: Best of Tuts+ in May 2012 | My Creative Directory

  • Pingback: Best of Tuts+ in May 2012 | SearchPsd Blog

  • Pingback: Best of Tuts+ in May 2012 | Clixto7

  • Pingback: Best of Tuts+ in May 2012 | http://www.piczap.com

  • Pingback: Best of Tuts+ in May 2012 | Wptuts+

  • Pingback: Best of Tuts+ in May 2012 | Wordpress Webdesigner

  • Pingback: Best of Tuts+ in May 2012 | Omega Pixels

  • Pingback: Best of Tuts+ in May 2012 | Flash Video Traning Source

  • Pingback: Best of Tuts+ in May 2012 |

  • Pingback: Best of Tuts+ in May 2012 | How to Web

  • Pingback: Best of Tuts+ in May 2012 | GMancer

  • Pingback: Wordpress Leaks » Best of Tuts+ in May 2012

  • Pingback: » Best of Tuts+ in May 2012 TNR Today

  • Patrick

    This is by far the best tutorial on WordPress I have ever read. I think I have learned more from this series than the last two books that I bought. However, when I check my index.php page I notice that only the content div is showing. Back in the admin page it shows that I have successfully saved the header and footer options but once I flip back over to index.php, no joy. I scoured every line code and can’t figure it out. I wouldn’t be surprised if it had something to do with a nonce or something like that.

    • Patrick

      Nevermind, I figured it out. On the index page I was still calling get_option['show_header'] instead of calling sandbox_theme_display_options and checking the show footer key.

      • Tom McFarlin
        Author

        Thanks for the kind words – and I’m glad you got it sorted. Nice work!

  • pepin

    Thanks for your great article, Learned a lot but I have one small questions, instead of writing all the options code in function.php, is it possible to write the code in file called options.php and call in the functions.php.

    Thanks and appreciate it

    • Tom McFarlin
      Author

      It’s possible, though I don’t recommend it. That’s not a WordPress best practice.

  • http://humboldteffectivewebdesign.com/ Ben Thvedt

    I have recently become interested in computer programming, I thought I could make websites for people to get experience, and that naturally led me to wordpress.. It’s been slow going but I’m progressing. This is probably the best tutorial I have read, and I am much more comfortable with writing wordpress php stuff now that I’ve worked through it. I finally feel like I’m kinda starting to know what’s going on. I’m off to read another one of your tutorials now, thanks.

  • http://webenvelopment.com Ben Racicot

    It looks like these practice files are FULL of php errors for the current WAMP setup. Not to sure what to do about it at this point.
    Anyone else?

    • Jake

      This is due to attempting to grab options when they haven’t been set, this can be fixed by checking if the option has been set using the native PHP function isset() prior to accessing the option.

      This is a great series Tom, thorough and well written. Good job!

  • http://www.itechplus.org/ N Atta Kusi Adusei

    Great tuts. Thanks :-)

  • Rishikant

    Thanks for this, i read all and learn alot.

  • http://www.rsatechnoloies.in rakesh kumar

    read all the eight articles on setting api. Let me consume all of them so that i can make changes in side m admin box. Thanks a lot my dear friend for this wonderful series.

  • Reinhard

    Thank you so much for sharing this AWESOME tutorial with us!
    You just made my day!

  • Jack

    Hi,

    Brilliant Tutorial.

    What i am trying to do is create a custom options page on my site where users can create new settings fields by clicking a button.

    For example i need to create a list of settings( setting 1, setting 2, setting 3 etc) and have users create more settings with the click of a button.

    Is this possible, does anyone know where there is a tutorial that may help?

    Thanks
    J

    • http://twitter.com/_Rashmirathi Rashmirathi Tiwari

      Dear Jack

      I hope you’d have found a solution to the problem you describe here.
      I will really appreciate if you can share the solution here.

      Thanks a lot mate!

  • http://www.adamcrooker.com adamTheGr8t

    One quick question / my data gets saved and I can out put the options into the page just fine. But when I refresh the admin page the select forms default back and don’t show the saved selection.

    • Umid Almatov

      check your code in this line:

  • Steven

    Tom

    Thank you so much for such great tutoring ! This is the best training process on the net so far I could find !

    cheers !

    Steven

  • miramez

    i installed to test it… I can see the 3 tags into theme options, but when i click over any menu, it goes nowhere

  • Justin

    THis is a fantastic tutorial. thank you for making my life easier!

  • http://www.wordpressguru.com.au/ Wordpress Developer Sydney

    Great Tutorials Tom.
    I really admire your time, thinking and coordination writing this blog series.
    Its explained so properly and is so readable regardless if you are unexperienced developer. Now I have clear understanding of the WP Settings API. Thanks Heaps.

  • Gabriele

    Thanks for this fantastic tutorial!!!

  • dan

    Tom you are the man! Awesome tutorial. I like how you hold us by the hand in the beginning and then throw us in the deep end towards the end. Great for learning. Thanks!

  • Paul

    Awesome tutorial, but one question. Is there way to reset settings? Thanks

  • http://twitter.com/fujianto Septian

    Thanks for the tutorial, really helpful for me to understand how the Theme Options work.
    Sadly, lots of codes is missing from this tutorial, I had to check your Github to find what’s wrong with my code, since the code on this tutorial not as updated as the one on Github. A bit frustrating, but a good experience nonetheless . Hope you can revisit this tuts soon since I’m not totally sure how this function that I found on Github works. Thx sandbox_theme_default_display_options() .

  • http://www.facebook.com/tommyboric Tomislav Borić

    Thought I’ll need at least a month to learn create my own settings page but with this AWESOME tutorial it took 2 days!!

    Thanks a lot Tom! Keep doing a great job!!!

    Greetings from Zagreb, Croatia!

  • Luismin

    Thanks for the amazing tutorial!

    I have only one question. Anybody knows if Is there any possibility to change the textarea for rich text element? I tried to use the function wp_editor but it does not show the content.How could I pass the id of the textarea?

    Thanks in advance

  • FeelX90

    This is definitely the best tutorial about the WordPress Settings API I’ve ever read… I don’t know why I didn’t find this earlier. I’m glad you divided it into multiple parts since all the articles which try to explain the API and its usage in one single post, they all lack one or another topic.

    Thank you very much for this series!