…Was tearing through a bunch of meta fields using CMB2 and noticed some unexpected behavior when I went to set a checkbox’s default value to true.
When I refreshed the admin — sure enough — the checkbox was checked.
Everything good right?
Well, had I saved it with a true value and went on my way then yes.
But as I usually do, I went looking for trouble.
The Problem
I…
- Cleared the corresponding database row for that field.
- Reloaded the WP admin.
- Unchecked the checkbox.
- And saved my changes.
Oh looky here.
The admin reloads but the checkbox is still checked?? WT…
It’s okay, don’t panic. This is only a minor setback.
You can simply add a callback function passed using the sanitization_cb field parameter and all should be right as rain.
The Workaround
First, add the field parameter like so:
$cmb2_box_blog->add_field([
'name' => __( 'Disable Blog', 'keystone' ),
'id' => 'cmb2_id_field_disable_blog',
'desc' => 'I\'m a checkbox!',
'type' => 'checkbox',
'sanitization_cb' => 'sanitize_checkbox',
'default' => true, //If it's checked by default
'active_value' => true,
'inactive_value' => false
]);
Now add the callback function somewhere in your theme or plugin, for example in your functions.php:
function sanitize_checkbox($value, $field_args, $field) {
// Return 0 instead of false if null value given.
return is_null($value) ? 0 : $value;
}
Now — when you repeat the steps above — you should see the checkbox in the admin in the desired state.
The Reason Why
CMB2 infers the value being saved as NULL and by design (as I understand it) does not save NULL values to the database.
When you go to refresh the admin you see the checkbox still checked because no value was written to the database — and so once again infers unchecked.
TTFN you little web assassins!