I’m developing a theme settings panel for a new wordpress theme that have an option to exclude categories from being shown in the loop. I managed to get the main functionality to work, using a mutilselect box and saving the values as array …
<?php $cats = get_categories('hide_empty=0&orderby=name'); ?>
<select name="<?php echo $option['id']; ?>[]" id="<?php echo $option['id']; ?>" multiple="multiple">
<option value="0">None (don't exclude anything)</option>
<?php foreach ($cats as $cat_list ) { ?>
<option value="<?php echo $cat_list->cat_ID; ?>" <?php selected( $selected, $cat_list->cat_ID ); ?>><?php echo $cat_list->cat_name; ?></option>
<?php } ?>
</select>
however I can’t understand how check every item in foreach()
loop if its value matches one value in the stored values array, then apply selected="selected"
if it returns true to it. I understand selected()
wp function but don’t understand how to make use of it in this case ( multiple values inside foreach()
loop ).
Any help will be appreciated, I’m a n00b so forgive me if it’s a stupid question 🙂
I’m assuming your
$selected
variable contains an array of values for the currently selected items?You can’t use selected in this case (with multi select boxes) because it only compares two strings. It won’t test to see if the value is in an array. Instead, use a ternary statement and
in_array()
I know this is an old question but still the answer was not answered using the core function…
Here it is:
Make sure
$selected
is an array of course that contains selected category ids.The Q is not stupid. Imo just the extremly confusing way it’s documented. I also remember that there’s somewhere in the codex written, that using
selected()
and similar stuff is a must(!). I don’t aggree.Anyway:
selected( 'one_value', 'val_to_compare_with', true );
Let’s make it simpler:
Here,
$selected
variable contains an array of values for the currently selected items.