如何在选中选项的情况下填充下拉菜单?

时间:2014-11-21 作者:RobbertT

我有这段代码来填充我的WP类别的自定义下拉菜单。现在一切正常,但我希望在下拉列表中选择当前类别。我该怎么做?

<select name="page-dropdown"
 onchange=\'document.location.href=this.options[this.selectedIndex].value;\'>
<?php

    hierarchical_category_tree( 0 ); // the function call; 0 for all categories; or cat ID  

function hierarchical_category_tree( $cat ) {
    // wpse-41548 // alchymyth // a hierarchical list of all categories //

  $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 ) . \'">\' . $cat->name . \'</option>\';

    hierarchical_category_tree( $cat->term_id );
    endforeach;    
 endif;

   echo "\\n";
}  
?> </select>
非常感谢您的帮助!非常感谢。

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

使用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";
}  

SO网友:Howdy_McGee

从该脚本的外观来看,只要单击一个选项,它就会将您重定向到任何类别存档,因为在这种情况下,我们只需获取用户登录的当前类别,并将当前类别ID与循环中的类别ID进行比较:

以下是修改后的代码:

<select name="page-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
  <?php
    hierarchical_category_tree( 0 ); // the function call; 0 for all categories; or cat ID  

    // Get current category
    $current_cat = get_queried_object();
    $curr_cat_id = ( is_category() ) ? $current_cat->term_id : -1;

    function hierarchical_category_tree( $cat ) {
        // wpse-41548 // alchymyth // a hierarchical list of all categories //
        $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 ) . \'" \' . ( $cat->term_id == $curr_cat_id ) ? \'selected="selected"\' : \'\' . \'>\' . $cat->name . \'</option>\';
                hierarchical_category_tree( $cat->term_id );
            endforeach;    
        endif;

        echo "\\n";
    }  
  ?>
</select>

结束