这并不难,但这次需要一些PHP编码。下面是实现该技巧的代码(假设该层次结构中只有2个级别):
$post_terms = get_the_terms( $post->ID, \'services\' );
$terms = array();
foreach ( $post_terms as $term ) {
if ( $term->parent ) {
if ( ! array_key_exists( $term->parent, $terms ) ) {
$terms[ $term->parent ] = array(
\'term\' => get_term( $term->parent, \'services\' ),
\'children\' => array()
);
}
$terms[ $term->parent ][\'children\'][] = $term;
} else {
if ( ! array_key_exists( $term->term_id, $terms ) ) {
$terms[ $term->term_id ] = array(
\'term\' => $term,
\'children\' => array()
);
}
}
}
foreach ( $terms as $term_info ) {
echo $term_info[\'term\']->name;
if ( ! empty($term_info[\'children\']) ) {
echo \': \';
foreach ( $term_info[\'children\'] as $i => $child ) {
if ( $i ) echo \', \';
echo $child->name;
}
}
echo "<br/>\\n";
}