这是一个可以像WordPress一样使用的函数get_categories 但返回层次结构数组。为此,有一个child_categories
属性添加到每个WP_TERM
对象:
function get_categories_hierarchical( $args = array() ) {
if( !isset( $args[ \'parent\' ] ) ) $args[ \'parent\' ] = 0;
$categories = get_categories( $args );
foreach( $categories as $key => $category ):
$args[ \'parent\' ] = $category->term_id;
$categories[ $key ]->child_categories = get_categories_hierarchical( $args );
endforeach;
return $categories;
}
例如,可以使用此函数(从类别层次结构的前两个级别构建一行HTML select输入):
<?php if( $categories = get_categories_hierarchical() ): foreach( $categories as $category ): ?>
<label for="filter_cat_<?php echo $category->term_id; ?>"><?php echo $category->name; ?></label>
<select name="filter_cat_<?php echo $category->term_id; ?>" id="filter_cat_<?php echo $category->term_id; ?>">
<?php if( $category->child_categories ) foreach( $category->child_categories as $subcategory ): ?>
<option value="<?php echo $subcategory->term_id; ?>"<?php if( $_GET[ \'filter_cat_\' . $category->term_id ] == $subcategory->term_id ) echo \' selected\'; ?>><?php echo $subcategory->name; ?></option>
<?php endforeach; ?>
</select>
<?php endforeach; endif; ?>
也请查看
wp_dropdown_categories 和
wp_list_categories wich已经可以做您需要的事情,而不需要额外的功能。