Adding a Checkbox Input to WordPress Settings
WordPress Settings
In previous articles in the WordPress Settings series we covered adding a settings page with a few basic fields. Throughout the series we’ve added a settings form with three text inputs, a textarea input, a WP Editor input, a password input, a select input, and a radio button input.
This article builds on the previous articles by adding a checkbox input to our existing settings.
Adding the Defaults
In a previous article we covered how every WordPress setting should have a default value assigned and how to add the defaults to your code. Below is an extended version of that code that includes the default settings for our new Checkbox input.
<?php
function ltdi_register_settings() {
/* Code for settings section goes here. */
if ( false == get_option( 'ltdi_theme_settings' ) ) {
$defaults = [
'setting_field_one' => '',
'setting_field_two' => '',
'setting_textarea_field' => '',
'setting_wp_editor_field' => '',
'setting_password_field' => '',
'setting_select_field' => '1',
'setting_radio_button_field' => 'value-01'
'setting_checkbox_field' => [] /* new default */
];
add_option( 'ltdi_theme_settings', $defaults );
}
}
add_action( 'admin_init', 'ltdi_register_settings' );
What is this code doing:
- We continue editing the “ltdi_register_settings” function from the previous article by adding a key/value pair for our “setting_checkbox_field”.
- For this tutorial the default value will be different. Because our field is a checkbox where multiple items can be selected the default value should be an empty array.
- Like the previous article, if no settings are found, the get_options() function will return false.
- When a false value is returned from get_option() we use the function add_option(), passing our settings unique identifier and the array of defaults as the first and second parameters respectively. Doing so will save the default settings to the database.
Adding the Checkbox Input
As mentioned in a previous article’s section “Adding the Setting Input Fields”, each field is added with a combination of the built-in function “add_settings_field” and a callback function for the specific field type.
Add Settings Field
For the checkbox input we start with the built-in function add_settings_field, using the arguments listed below.
$name
The first argument is the field $name. It is a required unique identifier for the setting. It should be a single string value usually formatted with underscores to combine multiple words. In this case it is “setting_checkbox_field”.
$title
The second argument is the field $title. It should be a string value formatted for display to the WordPress user. For this tutorial we will use the string “New Checkbox Setting”.
$callback
The third argument is the name of the $callback function that outputs the HTML. Because we are implementing a Checkbox input we will be using the name “ltdi_get_checkbox_input”.
$option_name
The fourth argument tells WordPress what group to add the setting to. For this tutorial we will use the string “ltdi_theme_settings” which is the name of our settings group.
$section_name
The fifth argument tells WordPress what section to associate our setting with. For this tutorial we will use the string “ltdi_theme_settings_section” which is the name of our settings section.
$args
Similar to the previous article “Adding Radio Buttons to WordPress Settings” , the Checkbox input args array uses three key/value pairs. The first two, “label_for” and “class” are the same. The third is used to provide the available options to our checkbox input.
<?php
function ltdi_register_settings() {
/* Code for settings section adding defaults goes here. */
/* Code that adds the fields in the previous article goes here. */
add_settings_field(
'setting_checkbox_field',
'New Checkbox Setting',
'ltdi_get_checkbox_input',
'ltdi_theme_settings',
'ltdi_theme_settings_section',
[
'label_for' => 'setting_checkbox_field',
'class' => 'setting_checkbox_field',
'options' => [
[
'value' => '1',
'label' => 'Option One'
],
[
'value' => '2',
'label' => 'Option Two'
],
[
'value' => '3',
'label' => 'Option Three'
]
]
]
);
Adding the Checkbox Callback Function
Although the field has been added to WordPress, before it can be used we need to create the callback function to output the checkbox’s HTML on the screen.
<?php
function ltdi_get_checkbox_input($args) {
$settings = \get_option('ltdi_theme_settings');
$selected = false;
echo '<fieldset>';
foreach ($args['options'] as $option) {
$nameAttr = "ltdi_theme_settings[{$args['label_for']}][]";
if (!empty($settings[$args['label_for']])) {
$selected = in_array($option['value'], $settings[$args['label_for']]);
}
checked($selected, true, false);
printf(
'<input type="checkbox" name="%1$s" value="%2$s" %5$s /><label for="%4$s">%3$s</label>',
$nameAttr,
$option['value'],
$option['label'],
$args['label_for'],
$checked
);
}
echo '</fieldset>';
}
What is this code doing:
- We start by declaring the function “ltdi_get_checkbox_input”.
- We then create a $settings variable that stores all of our settings by using the get_option() function with the argument “ltdi_theme_settings” to retrieve them.
- We then create a $selected variable and set it to false (the default value of each checkbox).
- After that we echo the opening “fieldset” tag.
- Then we loop through the “options” available in the $args variable.
- Directly within the loop we create a variable called $nameAttr that combines our settings unique identifier and the name of the field as the value. Remember the array brackets on the end of the name.
- We then verify if the checkbox settings has a value stored.
- Then within that conditional use the function in_array() to check if the option exists in our settings. If the option exists we change the value of the $selected variable to true.
- Then we use the checked() WordPress function to determine if the $selected variable is equal to true. If it is, the string “checked=”checked”” will be stored in the $checked variable.
- Then we use the printf() function with the values stored in the variables $nameAttr, $option[‘value’], $option[‘label’], $args[‘label_for’] and $checked to ouput the HTML for all the options.
- We finish by echoing the closing ‘fieldset’ tag.
Refactor the Sanitization Callback
There is one last thing we need to change. Because the stored value of our checkbox is an array we need to modify the sanitization function we created in the article “Add WordPress Settings Without a Plugin“.
<?php
function ltdi_setting_sanitization($input) {
$output = [];
foreach ($input as $key => $value) {
if (!isset($input[$key])) {
continue;
}
// New: Conditional to check if value is an array and proceed accordingly
if (is_array($value)) {
foreach($value as $index => $value) {
$output[$key][$index] = strip_tags(stripslashes($value));
}
} else {
$output[$key] = strip_tags(stripslashes($input[$key]));
}
}
return apply_filters( 'ltdi_setting_validation', $output, $input );
}
What is this code doing:
- The first line of code creates a variable called $ouput for storing the validated settings.
- We then loop through each of the incoming settings.
- Directly within the loop we verify if this setting has a value. If it doesn’t we use the keyword “continue” to start the loop over on the next value in the array.
- On the next line we check if the value is an array.
- If it is, we loop through each of its values, stripping HTML tags, PHP tags and properly handling quoted strings.
- Then we assign the value to our $output array with a key and index that matches the $input array.
- If the input is a string (not an array), we proceed to strip all HTML tags, PHP tags and properly handle quoted strings, assigning it to our output array.
- Finally we return the $output providing a filter so additional functions can process the data.
Putting It All Together
The final code is available for download on github. When this code is added to your WordPress theme’s function file or your plugin’s main file, you should have a functioning WordPress settings page with two text inputs, one textarea input, one WordPress Editor input, one password input, one select input, a group of radio buttons and our new checkbox input.
Remember: something as simple as a typo can take down a website. For this reason I recommend plenty of backups. I also recommend using a development environment to test the code before pushing it live.
Receive Tutorials Direct to Your Inbox