Add a Checkbox Control Using Customizer API in WordPress

The inbuilt WordPress customizer gives us a great way to customize a custom theme.

If you need a few theme settings added, you can do so with the customizer API which contains a very useful set of functions for this purpose.

The settings added to a custom theme can take many types of values. One such value is a Boolean value that can store either true or false.

A checkbox control is perfect for managing such a setting.

The syntax for a checkbox control is as follows –

 $wp_customize->add_control( 'setting_id', // required
     array(
        'label'      => 'My awesome label', // arbitrary string
        'section'    => 'section_id',  // required - section id
        'type'       => 'checkbox' // required
     ) 
);

The section_id can be from a new or existing section. Accordingly you may or may not need to create the section.

The type parameter determines the type of the control which is checkbox in this case.

You will also need to associate the checkbox control with a setting.

$wp_customize->add_setting( 'setting_id', 
   array(
      'default'        => true,
      'type'           => 'theme_mod',
      'capability'     => 'edit_theme_options',
      'sanitize_callback' => 'custom_sanitize_callback'
   )
);

The type parameter is either theme_mod or option. Custom themes typically use theme_mod as the setting is specific to that theme and not sitewide.

The capability parameter the permission level of the user which in this case is someone who can edit the theme options – usually an editor or administrator.

The sanitize_callback parameter takes a custom function custom_sanitize_callback as callback.

Since the control is checkbox, this function needs to sanitize the input to accept only a true or false value.

 //checkbox sanitization function
 function theme_slug_sanitize_checkbox( $input ){              
    //returns true if checkbox is checked
    return ( isset( $input ) && $input == true ? true : false );
 }

The default parameter in setting is set to true. Which means the checkbox will be ticked when the customizer window opens. You can change it to false depending on your requirements.

The checkbox control also needs a section. If the section is already existing then you do not need to write code for the section. You will only need the section_id.

If you are creating a new section with the control then the complete code will look like this –

function custom_customize_register() {
     // call to create a section
     // call to create a setting
     // call to create the control
}
add_action( 'customize_register',  'custom_customize_register' );

The customize_register hook is required to create the function that will contain the code for creating the customizer elements.

The custom_customize_register is the custom callback function for this hook.

The above code goes to functions.php file or within any place within the scope of functions.php