在过去的两天里,我一直在努力解决一个问题,但尽管我尽了全力,我似乎还是无法找到解决方案。
在后端,我为用户对象提供了一个名为“程序”的层次分类法。层次结构如下:
Parent
-- Child
--- Grand Child
我有一个前端用户设置表单,其中我使用以下代码输出此分类法的术语:
$args = array(\'hide_empty\' => false, \'hierarchical\' => true, \'parent\' => 0);
$terms = get_terms("program", $args);
$fieldName = "programs";
$html = \'\';
$html .= \'<select name="\' . $fieldName . \'"\' . \'class="programs"\' . \'>\';
foreach ( $terms as $term ) {
$selected = $terms[0]->term_id;
$html .= "<option value=\'".$term->term_id."\'".($selected == $term->term_id ? \' selected="selected"\' : \'\').">" . $term->name . \'</option>\';
$args = array(
\'hide_empty\' => false,
\'hierarchical\' => true,
\'parent\' => $term->term_id
);
$childterms = get_terms("program", $args);
foreach ( $childterms as $childterm ) {
$selected = $childterms[0]->term_id;
$html .= "<option value=\'".$term->term_id."\'".($selected == $childterm->term_id ? \' selected="selected"\' : \'\').">" . $term->name . \' > \' . $childterm->name . \'</option>\';
$args = array(\'hide_empty\' => false, \'hierarchical\' => true, \'parent\' => $childterm->term_id);
$granchildterms = get_terms("program", $args);
foreach ( $granchildterms as $granchild ) {
$selected = $granchildterms[0]->term_id;
$html .= "<option value=\'".$term->term_id."\'".($selected == $granchild->term_id ? \' selected="selected"\' : \'\').">" . $term->name . \' > \' . $childterm->name . \' > \' . $granchild->name . \'</option>\';
}
}
}
$html .= "</select>";
echo $html;
这段代码输出以下HTML,虽然在我提交表单时,正确的分类术语被保存在数据库中,但前端表单始终显示选中的“Grand Child 1”,即使在数据库中设置了“parent”或“Child”。我还看到前3个选项被设置为选中,而在任何给定时间只有一个选项被设置为选中:
<select name="programs" class="programs">
<option value="6" selected="selected">Parent</option>
<option value="7" selected="selected">Parent > Child 1</option>
<option value="8" selected="selected">Parent > Child 1 > Grand Child 1</option>
<option value="9">Child 2</option>
</select>
下面是$terms(parent)变量的转储:
Array
(
[0] => stdClass Object
(
[term_id] => 6
[name] => Parent
[slug] => parent
[term_group] => 0
[term_taxonomy_id] => 6
[taxonomy] => program
[description] =>
[parent] => 0
[count] => 0
)
)
1
请帮忙!非常感谢!