[WordPress]termを階層表示する
termを階層表示したい場合。
多階層の場合は再帰を使うと便利。というか、階層の深さが決まっていない場合は再帰を使うしかありません。
まずは再帰の為にfunctionを作ります。
functions.phpに置いておいてもいいのかも。
<?php
function output_terms( $this_id ){
if( !$this_id ) $this_id = 0;
$taxonomy = 'taxonomy_name';
$args = array(
'parent' => $this_id
// , hide_empty => 0 //記事無しのtermも表示したい場合はコメントアウトを解除しよう
);
$terms = get_terms( $taxonomy, $args );
if( count($terms) > 0 ){
if( $this_id != 0 ) echo '<ul>';
foreach ( $terms as $term ) {
echo '<li><a href="' . esc_url( get_term_link( $term->term_id )) . '">' . $term->name . '</a>';
output_terms($term->term_id); //ここで再帰して子孫termを表示
echo '</li>';
}
if( $this_id != 0 ) echo '</ul>';
}
}
?>
引数0または無しで呼び出すと最上位(親無し)から書き出せます。
任意のtermがある場合は、初期の呼び出しをそのtermのIDにすればOK。
手打ちで「全記事」とか足したい場合用に、親無しの場合は、ulタグの出力をしないようにしてあります。
任意のtermからスタートする場合で何か静的に足したい場合は、上のコード中の「if( $this_id != 0 )」の2か所を書き換えればOK。
呼び出し部分の記述はこんな感じです。
<ul> <li><a href="#">全記事</a></li> <?php output_terms(0); ?> </ul>
