Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 :)

share|improve this question

2 Answers 2

up vote 2 down vote accepted

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()

<?php 
foreach ($cats as $cat_list ) { 
$selected = in_array( $cat_list->cat_ID, $selected ) ? ' selected="selected" ' : '';    
?>
    <option value="<?php echo $cat_list->cat_ID; ?>" <?php echo $selected; ?>><?php echo $cat_list->cat_name; ?></option> 
<?php } ?>
share|improve this answer
    
He is asking about the core function :) –  kaiser Aug 29 '11 at 0:23
    
@Christopher Thank you very much, this solved my situation. I'm a php noob, that's why I couldn't find the suitable way myself. Thanks a lot again :) –  user8220 Aug 29 '11 at 1:06

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 );

share|improve this answer
    
thank you kaiser, I just wanted to achieve the same result but with an array of values instead of a single value. Christopher's answer is what I was seeking for. Thank you, I appreciate your interest. –  user8220 Aug 29 '11 at 1:12
    
You're welcome :) –  kaiser Aug 29 '11 at 2:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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