Since WordPress.org theme review team asked all theme authors to implement the Customizer for their theme options, how to leverage the core customizer controls is important for any theme authors.
Core provides several built-in control types:
- checkbox (it’s single checkbox)
- radio (pass a keyed array of values => labels to the choices argument)
- select (pass a keyed array of values => labels to the choices argument)
And also core provides some custom controls:
These controls are not always meeting our needs so WordPress provides us a class (WP_Customize_Control) to create our own custom controls. Actually this is also the parent class for the classes listed above.
Today I am going to show you how to create a multiple checkbox control as this is many people are looking for.
And following working codes are from one of my custom themes created recently.
Let’s look at the final work of today’s tutorial.
First let’s build the Multiple Checkbox class.
You can paste these codes to your
You’ll also see we have enqueued a js file
customize-controls.js, in this case it’s located in
theme root/js/ folder.
One thing to get your notice is that there’s a hidden
input element, which we’ve added the standard
$this->link() output to. We’ll be dynamically adding the checkbox input values to this hidden input via
customize-controls.js so that it works with the customizer.
It’s done. Below is a simple example to get you started.
Remember this should go to your
customize_register action hook as any other built-in controls.
It is usually most important to set the default value of the setting as well as its sanitization callback, which will ensure that no unsafe data is stored in the database.
Here is the sanitization of the multiple checkbox value.
keep in mind that because we used a hidden input element in our control, everything is stored as a comma-delineated string of values rather than array. So, we’ll need to turn that back into an array before the value is saved to the database.