0

I'm creating a page options which contain some multiple checkboxes with specific values. Here is a snippet of my checkboxes form code:

   <label>Global Checkboxes</label>
   <input style="width:0;" type="checkbox" name="page_options[check_list_global][0]" value=“check1" <?php checked( $options['check_list_global’][0], ‘check1'); ?> />
   <label>Check 1</label>
   <input style="width:0;" type="checkbox" name="page_options[check_list_global][1]" value=“check2" <?php checked( $options['check_list_global'][1], ‘check2'); ?> />
   <label>Check 2</label>
   <input style="width:0;" type="checkbox" name="page_options[check_list_global][2]" value=“check3" <?php checked( $options['check_list_global'][2], ‘check3'); ?> />

Then I can just get the values with a regular for loop and perform string operations to the $output. This works and suffices my needs.

for ($i = 0; $i < 3; ++$i) {
   print $options['check_list_global’] [$i];
}

But I feel there has to be a better approach. Ideally I would like to store all the values of the checked boxes in a single page_options['check_list_global'] in the format of key : value or similar. Getting rid of the [$number] after the option. This way I don't have to hardcode all my fields, be more clean, efficient and of course, dynamic if more is needed to be added.

So i think my question can be summarized:

How can I store all the values of the checklist as an array and avoid having to specify the [$number] in each of my fields?

I hope I was clear enough, thank you!

1

After much experimentation I resolved my own question and this answer might help somebody.

    function mmm_select_field(  ) {

    $options = get_option( 'mmm_settings' );

    $buttons = array(
        'Bold' => 'bold',
        'Italic' => 'italic',
        'Underline' => 'underline',
        'Superscript' => 'superscript',
        'Align Left' => 'alignleft',
        'Align Center' => 'aligncenter',
        'Align Right' => 'alignright',
        'Bullet List' => 'bulletlist',
        'Number List' => 'numberlist',
        'Link' => 'link',
        'Unlink' => 'unlink'
    );

    foreach ($buttons as $key => $value) { ?>
        <input name="mmm_settings[mmm_select_field][]" type="checkbox" value='<?php echo $value; ?>' <?php if((!empty($options['mmm_select_field']) && in_array($value, $options['mmm_select_field']))) { echo "checked"; } ?>/>
        <label for="<?php echo $value ?>"><?php echo $key; ?></label>
    <?php }

    }

Basically this is how you assign the array to an Option/Setting:

mmm_settings[mmm_select_field][]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.