How to deal with multiple select options using register_setting() theme options

I’m using Ian Stewart’s Sample Theme Options for a lightweight Theme Options panel.

INSERTION FAILED

I need to insert Multiple categories into db, where I used the following code:

<select multiple="multiple" name="site_options[categorychoice]">
   <?php
   $args = array(
        'orderby' => 'name',
        'parent' => 0,
        'exclude' => 1
     );
   $categories = get_categories( $args );
   foreach ($categories as $category) { ?>
        <option value="<?php echo $category->term_id; ?>" style="padding-right: 10px;" <?php selected( $site_options['categorychoice'], $category->term_id ); ?> ><?php echo $category->cat_name . ' (' . $category->category_count .')'; ?></option>
   <?php }  ?>
</select>

On the validation portion of the code:

function theme_options_validate( $input ) {
   $got_categories = array( $input['categorychoice'] );
}

It is inserting data into Options table, but not multiple, it’s inserting the last selection only. So what I got is: 'categorychoice' => string '5' (length=1) — only a single value among all, and the that’s the last cat_id among the selected.

SELECTED=SELECTED FAILED

I’m also failing to make the value selected, when that matches the data with the db. I tried my code with This WPSE solution, but failed:

foreach ($categories as $category) { ?>
     <?php $selected = in_array( $category->cat_ID, $selected ) ? ' selected="selected" ' : '' ?>
     <option value="<?php echo $category->term_id; ?>" style="padding-right: 10px;" <?php echo $selected; ?> ><?php echo $category->cat_name . ' (' . $category->category_count .')'; ?></option>
<?php } ?>

2 Answers
2

The problem here is that you don’t allow PHP to read more than one value, because all values use the same name site_options[categorychoice], so they overwrite each other, and the last one wins.

You need more brackets. Set the name attribute of your select element to site_options[categorychoice][], and all values will be read by PHP.

Leave a Comment