タクソノミーページで子孫要素を取得する方法です。
これが活用できる場面は
(例)
車
↓
→軽自動車,普通自動車,大型自動車,
↓
-→メーカーA,メーカーB,メーカーC,…
例えば、軽自動車一覧のページで、メーカー別に軽自動車のページを表示させたい場合に、
メーカー一覧のメニューを表示でき、メーカー別に一覧を表示した際にも、メーカー一覧を表示したままにできる点です。
下記のコードを、使用することで、
タクソノミーページで子孫要素、ここでは(メーカーA,メーカーB,メーカーC,…)などの一番下の要素で、
常に表示させておくおことができます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php // タームIDの取得と表示 //現在のタームのidを取得 $taxonomy_name = 'work-cat'; $term_id = get_queried_object()->term_id; $terms = get_terms("work-cat","include=".$term_id); $childs = get_term_children( $term_id, $taxonomy_name ); if(count($childs) > 0){ $parent_id = $term_id; }else{ $parent_id = $terms[0]->parent; } $termchildren = get_term_children( $parent_id, $taxonomy_name ); echo '<ul class="cat-nav">'; foreach ( $termchildren as $child ) { $term = get_term_by( 'id', $child, $taxonomy_name ); echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>'; } echo '</ul>'; ?> |
コメント