Using Wordpress I have created a multiple select box so that users can select categories to exclude. When the page initially loads 开发者_StackOverflowI see my default values pre-selected. However when I select new values and save... I only see the word "Array" echoed and nothing selected?
<select class="amultiple" id="<?php echo $value['id']; ?>" name="<?php echo $value['id']; ?>[]" multiple="multiple" size="8">
<?php
global $options;
foreach ($options as $value) {
if (get_settings( $value['id'] ) === FALSE) { $$value['id'] = $value['std']; } else { $$value['id'] = get_settings( $value['id'] );
}
}
$categories = &get_categories('type=post&orderby=name&hide_empty=1');
if ($categories) {
$ex_cat = implode(',', $tt_cat_exclude);
foreach ($categories as $category) {
$selected = (in_array($ex_cat, $category->cat_ID)) ? ' selected="selected"' : '';
echo '<option value="' . $category->cat_ID . '"' . $selected . '>' . $category->cat_name . '</option>' . "\n";
}
}
?>
</select>
<br />For testing purposes, print variables: <?php echo $ex_cat; ?>
http://i48.tinypic.com/k9e3qq.gif
You should use implode()
Like so
$ex_cat = implode(',', $tt_cat_exclude);
This will return a comma separated list
This line should be
$selected = (in_array($category->cat_ID, $ex_cat)) ? ' selected="selected"' : '';
Changed to
$selected = (in_array($category->cat_ID, $tt_cat_exclude)) ? ' selected="selected"' : '';
Since the $ex_cat
is a string and cannot be used in in_array()
The $ex_cat
is now redundant i guess.
Looks like tt_cat_exclude
is missing it's opening $
name="tt_cat_exclude[]" means you're defining an array, so it's normal for the output to be "array"
for testing try print_r (outputs the whole architecture of the variable) or var_dump (outputs the var type too)
When you postback, the field tt_cat_exclude
is an array of the values that you've set - because you've name it tt_cat_exclude[]
with a []
behind.
Example:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select class="amultiple" id="tt_cat_exclude" name="tt_cat_exclude[]" multiple="multiple" size="8">
<option value="1">TestingA</option>
<option value="2">TestingB</option>
<option value="3">TestingC</option>
<option value="4">TestingD</option>
<option value="5">TestingE</option>
</select>
<input type="submit" value="Submit" />
</form>
<br/><br/>For testing purposes: <?php
if(isset($_POST['tt_cat_exclude'])){
var_dump($_POST['tt_cat_exclude']); // outputs an array of the selected values
}
?>
精彩评论