仅显示下拉列表中的第一个子项

时间:2014-08-31 作者:Guit4eva

我有一个下拉列表,显示了具有多个级别(子级)的自定义分类法。下面是它的代码。有人能解释一下我如何限制孩子们观看吗?例如,目前它显示:

父->子->子对象的子对象

我只想让它显示:

父->子级

谢谢!:)

function my_dropdown_categories( $taxonomy, $current_selected = \'\', $include = null ) {
// Get all terms of the chosen taxonomy
$terms = get_terms($taxonomy, array(\'orderby\' => \'name\'));

// our content variable
$list_of_terms = \'<select id="location" data-placeholder="Choose your area..."  class="selectboxSingle" name="location">\';

if ( ! is_wp_error( $terms ) ) foreach($terms as $term){

    // If include array set, exclude unless in array.
    if ( is_array( $include ) && ! in_array( $term->slug, $include ) ) continue;

    $select = ($current_selected == $term->slug) ? "selected" : ""; // Note: ==

    if ($term->parent == 0 ) {

        // get children of current parent.
        $tchildren = get_term_children($term->term_id, $taxonomy);

        $children = array();
        foreach ($tchildren as $child) {
            $cterm = get_term_by( \'id\', $child, $taxonomy );
            // If include array set, exclude unless in array.
            if ( is_array( $include ) && ! in_array( $cterm->slug, $include ) ) continue;
            $children[$cterm->name] = $cterm;
        }
        ksort($children);

        // OPTGROUP FOR PARENTS
        if (count($children) > 0 ) {
        //     $list_of_terms .= \'<optgroup label="\'. $term->name .\'">\';
             if ($term->count > 0)

                 $list_of_terms .= \'<option class ="group-result" value="\'.$term->slug.\'" \'.$select.\'>\' . $term->name .\' </option>\';
        } else
            $list_of_terms .= \'<option value="\'.$term->slug.\'" \'.$select.\'>\'. $term->name .\' </option>\';
        //$i++;

        // now the CHILDREN.

        foreach($children as $child) {
          //   $select = ($current_selected == $child->slug) ? "selected" : ""; // Note: child, not cterm
             $list_of_terms .= \'<option value="\'.$child->slug.\'" \'.$select.\'>\'. $child->name.\' </option>\';
        } //end foreach

        if (count($children) > 0 ) {
            $list_of_terms .= "</optgroup>";
        }
    }
}

$list_of_terms .= \'</select>\';

return $list_of_terms;
}

1 个回复
SO网友:Rarst

get_term_children() 按目的是递归的,它将始终获取所有子级,并且不可配置。

get_terms() 是更通用的术语检索功能。使用parent 它的参数将只检索一个级别的子级(而child_of 将检索所有)。有关详细信息,请参阅Codex中的链接文档。

结束

相关推荐

WP_DROPDOWN_PAGES默认值

我有一个页面下拉菜单,但在我转到所选页面后,让我们说“关于我们”,dropbown的默认标题按钮是页面的标题,“关于我们”,因此我希望标题/默认选项是“请选择页面”或类似的内容。我的代码是:wp_dropdown_pages(\"title_li=&depth=1&sort_column=menu_order&child_of=\".$post->post_parent.\"&echo=0&selected=$currPage\"); 我做错了什么,