使用selected
HTML属性。See w3schools docs.
在foreach循环中,检查当前类别是否与当前迭代匹配,并添加selected
归因于那个option
要素您已经获得了每个术语的ID,因此您还需要获得当前类别ID,以便可以对照它进行检查。也许我会用get_the_category, 获取当前类别。
EDIT: 这是您更新的函数。新行已注释:
function hierarchical_category_tree( $cat ) {
// grab the current category object
$current = get_the_category();
$next = get_categories(\'hide_empty=false&orderby=name&order=ASC&parent=\' . $cat);
if( $next ) {
foreach( $next as $cat ) {
echo \'<option value="\' . get_category_link( $cat->term_id ) . \'"\';
// if the current category object matches the current ID of the iteration
// add the selected attribute to the option element
if ($current[0]->term_id == $cat->term_id) {
echo \'selected\';
}
echo \'>\' . $cat->name . \'</option>\';
hierarchical_category_tree( $cat->term_id );
}
}
echo "\\n";
}