Advertisement
Theme Development

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

by

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

Related Posts
  • Web Design
    eCommerce
    Taking Shopify Theme Development FurtherShopify thumb
    In this final part of our Shopify series we will look at how a deeper knowledge of Liquid will enable you to make your themes even more flexible. This will help you deliver richer and more imaginative store designs.Read More…
  • Code
    Theme Development
    Custom Controls in the Theme CustomizerTheme customizer custom control 400
    In the last article, we explored the advanced controls available in the Theme Customizer, and how to implement them. We’re going to look at how to create our own custom control, allowing you to choose which Category of Posts are displayed on the home page. To get started, download version 0.6.0 of our Theme Customizer Example.Read More…
  • Code
    Theme Development
    A Guide to the WordPress Theme Customizer: Advanced ControlsTheme customizer 400
    Throughout this series, we've been taking a look at the Theme Customizer, how to implement it in our themes, how to save, serialization, retrieve settings, and how to implement the options so that they automatically refresh whenever the options are updated. As we begin to wind down the series, we're going to be taking a look at the advanced controls offered by WordPress, and how to implement one of them in our theme. Then we'll be reviewing some of the resources that are available for those of you who opt to consider researching, implementing, and leveraging the Theme Customizer in your day-to-day work. But first, let's begin by taking a look at some of the controls that are offered natively with WordPress.Read More…
  • Code
    Theme Development
    A Guide to the WordPress Theme Customizer: A Methodology for Sections, Settings, and Controls – Part 2Theme customizer 400
    In the last article, we defined a simple methodology for everything that's required to establish a new Section, Settings, and Controls within the Theme Customizer. In this article, we're going to continue with doing more of the same; however, we're going to be adding new settings and controls into the existing section, but we're going to be looking at a variety of different options such as radio buttons, select boxes, and input boxes. So with that said, let's continue.Read More…
  • Code
    Theme Development
    A Guide to the WordPress Theme Customizer: A Methodology for Sections, Settings, and Controls - Part 1Theme customizer 400
    At this point in the series, we've covered everything from understanding why the Theme Customizer is beneficial to those of us who are designers and developers, how to implement it in our theme, and understanding the relationship between sections, settings, and controls. We've also taken a look at how to implement our own setting and control into one of WordPress' predefined sections. In this article, we're going to take a look at what's required to introduce our own section and a variety of settings and controls. This article will cover a methodology that can be followed for implementing new settings and controls, and how to apply this methodology for introducing a new section, setting, and control. We'll expand on this topic in the second part of this article by introducing additional controls. But, for now, let's take a look at the methodology, and let's introduce a new setting into the Theme Customizer.Read More…
  • Code
    PhoneGap
    PhoneGap: Build a Feed Reader - Project StructurePhonegap feed reader@2x
    Although not specifically created to work together, jQuery Mobile and Cordova (also known as PhoneGap) are a very powerful duo to create hybrid, mobile apps. This series will teach you how to develop a feed reader using web technologies and these two frameworks. Over the course of this series, you'll also become familiar with the Cordova Connection and Storage Core Plugins and the Google Feed API.Read More…