how to sanitize customizer checkbox control


When trying to use a sanitization callback for a value which I would like to store as boolean, I keep getting an error in the Customizer saying “Invalid input” for a checkbox (the error appears almost a minute after checking or unchecking the checkbox, and prevents me from “publishing” the changes).

Here is my sanitization function:

function sanitize_boolean($input){
    if(!isset($input)){ return false; }
    $retval = false;
        if($input == 'true' || $input == '1' || $input == 'on' || $input == 'yes'){
            $retval = true;
        if($input === 1){
            $retval = true;
        $retval = $input;
    return $retval;

Am I doing something wrong in my sanitization function which causes the “Invalid input” error in the Customizer?

I’m storing values as option array. Say my option name is ‘BVALS’. In my php, $BVALS is an array of attributes which are being stored as the option ‘BVALS’, which is synchronized with a Gutenberg block’s attributes. Say one of the attributes is ‘HASBOLDSTYLE’. When defining the attributes for the Gutenberg block I set the type to ‘boolean’, and when the value is saved and I inspect the database record I see that it is being stored correctly as boolean 1 or 0 (under ‘option_name’ ‘BVALS’ I find
‘a:61:{‘ (so an array with 61 elements) and then I find somewhere within the serialized array s:12:’HASBOLDSTYLE’;b:0;. If I change the attribute from false to true (let’s say with a checkbox) in my Gutenberg block’s InspectorControls and then update the option, I see the value is updated correctly s:12:’HASBOLDSTYLE’;b:1;.

Now I’m trying to use a control in the Customizer to read or write that same value.

I have something like this:

        'default'               => $attributes['HASBOLDSTYLE']["default"], //use same default value as for Gutenberg block attributes
        'type'                  => 'option',
        'capability'            => 'manage_options',
        'transport'             => 'postMessage',
        'sanitize_callback'     => 'sanitize_boolean'

        'label'     => 'Bold style',
        'settings'  => 'BVALS[HASBOLDSTYLE]',
        'priority'  => 10,
        'section'   => 'custom_styles',
        'type'      => 'checkbox'

And of course the sanitization callback as defined at the top. Every time I try to check or uncheck the checkbox in the Customizer, I get ‘Invalid value’ above the checkbox after about a minute. I’m able to sanitize and set any other value types: integer, float, and string (using absint, floatval, and wp_filter_nohtml_kses respectively), however boolean values with checkboxes are giving me errors preventing me from saving the values to the option.

, JohnRDOrazio 3 years 2020-06-01T15:10:19-05:00 0 Answers 88 views 0

Leave an answer