Отображать категории с дочерней категорией, разделенной буквой
Я пытаюсь показать как родительские, так и дочерние категории моего пользовательского типа сообщений, разделенные первой буквой категории
Что у меня есть.
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
1 answers
Вы должны просто иметь возможность добавить еще один цикл foreach, используя функцию 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>';
}
(непроверенный)
Вы могли бы сделать этот метод намного красивее, если бы сделали его рекурсивным;) Но я думаю, что этого должно хватить.
0
Author: simonthesorcerer, 2015-11-05 19:46:43