显示由字母分隔的子类别的类别

时间:2015-11-04 作者:lievo4

我试图显示自定义帖子类型的父类别和子类别,它们由类别的第一个字母分隔

我所拥有的。

A.
Apples

B. 
Bananas

C. 
Coconuts
我想要什么

A.
Apples<br />
-Red<br />
-Green<br />

B. 
Bananas

C. 
Coconuts
这是我现在掌握的代码。我也需要它来显示子类别。提前感谢。

<?php 
$list = \'\';
$args = array(
    \'hide_empty\' => true,  // Set this to true to hide terms with no posts
    \'hierarchical\' => true,
    \'pad_counts\' => false 
);
$tags = get_terms(\'type\',$args);
$groups = array(  );

if( $tags && is_array( $tags ) ) {
    foreach( $tags as $tag ) {
        $first_letter = strtoupper( $tag->name[0] );
        $groups[ $first_letter ][] = $tag;
}
if( !empty( $groups ) ) {
    $index_line = \'\';
    foreach( $groups as $letter => $tags ) {
        $list .= \'<h4><p id="\' . apply_filters( \'the_title\', $letter ) . \'"><strong>\'. apply_filters( \'the_title\', $letter ) .\'</strong></P></h4><hr><ul>\';
    foreach( $tags as $tag ) {
        $name = apply_filters( \'the_title\', $tag->name );
        $list .= \'<li><a href="\' . get_term_link( $tag ) . \'" title="\' . sprintf(__(\'View all posts tagged with %s\', \'\'), $tag->name) . \'">\' . $tag->name . \' </a></li>\';
  }
  $list .= \'</ul>\'; 
}
$list .= \'\';
}
} else $list .= \'<p>Sorry, but no tags were found</p>\';

print ($index_line);
print ($list);

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

您只需使用get_term_children() 作用

更改您的行:

foreach( $tags as $tag ) {
    $name = apply_filters( \'the_title\', $tag->name );
    $list .= \'<li><a href="\' . get_term_link( $tag ) . \'" title="\' . sprintf(__(\'View all posts tagged with %s\', \'\'), $tag->name) . \'">\' . $tag->name . \' </a></li>\';
}
。。。到

foreach( $tags as $tag ) {
    $name = apply_filters( \'the_title\', $tag->name );
    $list .= \'<li><a href="\' . get_term_link( $tag ) . \'" title="\' . sprintf(__(\'View all posts tagged with %s\', \'\'), $tag->name) . \'">\' . $tag->name . \' </a>\';

    // show children in their own ul
    if($children = get_term_children($tag->ID, \'type\')) {
        $list .= \'<ul>\';
        foreach($children as $child) {
            $list .= \'<li><a href="\' . get_term_link( $child ) . \'" title="\' . sprintf(__(\'View all posts tagged with %s\', \'\'), $child->name) . \'">\' . $tag->name . \' </a></li>\';
        }
        $list .= \'</ul>\';
    }

    // close li after this one
    $list .= \'</li>\';
}
(未经测试)

如果使用递归方法,可以使此方法更加漂亮;)但我觉得应该这样。