在选择菜单中比较当前帖子类别

时间:2012-07-06 作者:Sagive

我已经做过很多次了,但不是通过表格,所以当我试图根据当前的学期后id分配一个“选定的”时,我遇到了一个奇怪的问题。。。

可能是使用_the_category 然后get_categories 制造冲突?有人知道为什么会这样吗?

无论所选项目是最后一个项目,而不是当前帖子(通过外部表单获取帖子id)类别

这是我的代码:

<?php 
$postId = $_POST[\'postid\']; // the value is recieved properly
$currentCategory = get_the_category($postId);  // the value is recieved properly
$currentCategoryId = $currentCategory[0]->term_id; // the value is assigned properly

$categories = get_categories(\'hide_empty=0\'); // the value is recieved properly
$optionname = "postcats"; // the value is recieved properly
$emptyvalue = "";

// SELECET DROP DOWN TERMS
echo \'<select name="\'.$optionname.\'" class="clientList"><option selected="\'.$selected.\'" value="\'.$emptyvalue.\'">\'.__(\'Choose a category\',\'sagive\').\'</option>\';
foreach($categories as $category){
    // next line seem to not work!
    if($currentCategoryId == $category->term_id) {$selected = \'selected="selected"\';}
    echo \'<option name="\'.$category->term_id.\'" value="\'.$category->term_id.\'" \'.$selected.\'>\'.$category->name.\'</option>\';
}

echo \'</select>\';
?>

if i try to echo the $currentCategoryId outside the foreach it works
but not inside it.. kinda weird!

1 个回复
最合适的回答,由SO网友:Sagive 整理而成

OMG-我无法清除“$选定”值。。。希望这对像我一样一时糊涂的人有所帮助

<?php 
$postId = $_POST[\'postid\']; // the value is recieved properly
$currentCategory = get_the_category($postId);  // the value is recieved properly
$currentCategoryId = $currentCategory[0]->term_id; // the value is assigned properly

$categories = get_categories(\'hide_empty=0\'); // the value is recieved properly
$optionname = "postcats"; // the value is recieved properly
$emptyvalue = "";

// SELECET DROP DOWN TERMS
echo \'<select name="\'.$optionname.\'" class="clientList"><option selected="\'.$selected.\'" value="\'.$emptyvalue.\'">\'.__(\'Choose a category\',\'sagive\').\'</option>\';
foreach($categories as $category){

    // HERE I ENTERED AN ELSE THAT WOULD CLEAN
    // THE VALUE OF $SELECTED

    if($currentCategoryId == $category->term_id) {$selected = \'selected="selected"\';} else {$selected = \'\'}
    echo \'<option name="\'.$category->term_id.\'" value="\'.$category->term_id.\'" \'.$selected.\'>\'.$category->name.\'</option>\';
}

echo \'</select>\';
?>

结束