I'm using Settings API and I can't get checkboxes to work, if they're set to "false" they're not even being $_POST and that's the point.
Stephen Harris & Chip Bennett explained it, but I believe their way is not simple enough (especially for me, not PHP-guy at all). Do I REALLY need a few custom PHP functions and custom-named submit buttons for every form just to get this simple thing working?
My settings look much like:
register_setting('XX_theme_settings', 'XX_theme_settings', 'setting_validate' );
add_settings_section('theme_options', 'Theme Options', 'theme_options_generate', 'page1' );
add_settings_field( 'XX_Option1', 'Option 1', 'checkbox', 'page1', 'theme_options', 'XX_Option1', $args = array('id' => 'checkbox1', 'type' => 'checkbox') );
add_settings_field( 'XX_Option2', 'Option 2', 'checkbox', 'page1', 'theme_options', 'XX_Option2', $args = array('id' => 'checkbox2', 'type' => 'checkbox') );
Then I generate checkboxes with this callback function:
function checkbox($args) {
$options = get_option('XX_theme_settings');
echo '<input type="checkbox" name="'. $args['id'] .'" value="true"'; if($options[$args['id']]==true) { echo 'checked="checked'; }; echo '/>';
echo $args['type'];
}
Now, everything I need is a good validate callback:
function setting_validate($input) {
// Firstly it should find all fields of type == "checkbox"
// (I'm not sure why should I check which field was just being sent,
// is updating all the checkboxes from different sections a big no-no?
// it is much easier indeed.
// Now set the ones missing to false/0 and the rest to true/1.
// Then merge everything like below:
$options = get_option('XX_theme_settings');
$merged = array_merge($options, $input);
return $merged;
}
So the question is: how to list all Settings Api checkboxes and then set the right ones to true?
I guess it'd look something like that:
$options = array(
array(
'id' => 'checkbox1',
'type' => 'checkbox',
'page' => 'page1',
),
array(
'id' => 'checkbox2',
'type' => 'checkbox',
'page' => 'page1',
),
);
function setting_validate($input) {
foreach($options as $option) {
if($option['type'] == "checkbox") {
//set it to 1 if sent
}
}
$options = get_option('XX_theme_settings');
$merged = array_merge($options, $input);
return $merged;
}
Thanks :)
Here's how Chip Bennett does it exactly, but even with all these great comments I can't get how it exactly works.