WordPress4.6から追加されたWP_Term_Queryを使って、タームの一覧を出力する方法をご紹介いたします。
基本的な使い方は、get_termsと似ています。
スポンサードリンク
WP_Term_Queryを使ってタームの一覧を出力する方法
タームの一覧を出力したい場所に、以下のようなコードを記述します。
<?php $args = array( 'taxonomy' => 'タクソノミー名', 'orderby' => 'name', //名前でソート 'order' => 'ASC', //ASC:昇順(初期値)、DESC:降順 'hide_empty' => false //true:投稿がないタームの非表示、false:全て表示 ); $the_query = new WP_Term_Query($args); foreach($the_query->get_terms() as $term){ echo $term->term_id; //タームID echo $term->name; //ターム名前 echo $term->slug; //タームスラッグ echo $term->term_taxonomy_id; //タームが属するタクソノミーのID echo $term->taxonomy; //タームが属するタクソノミーの名前 echo $term->description; //タームの説明 echo $term->parent; //親タームのID echo $term->count; //タームが使われている投稿数 } ?>
例えば、投稿数付きのターム一覧を出力したい場合は、以下のように記述します。
<?php $args = array( 'taxonomy' => 'タクソノミー名', 'orderby' => 'name', //名前でソート 'order' => 'ASC', //ASC:昇順(初期値)、DESC:降順 'hide_empty' => false //true:投稿がないタームの非表示、false:全て表示 ); $the_query = new WP_Term_Query($args); foreach($the_query->get_terms() as $term){ $term_link = get_term_link($term->slug,$taxonomy_slug); //タームアーカイブのリンク取得 echo '<a href="'.$term_link.'">'.$term->name.' <span>'.$term->count.'</span></a>'; } ?>
ある特定の親タームに属する子ターム一覧を出力する場合は、以下のようになります。
<?php $args = array( 'taxonomy' => 'タクソノミー名', 'orderby' => 'name', //名前でソート 'order' => 'ASC', //ASC:昇順(初期値)、DESC:降順 'hide_empty' => false, //true:投稿がないタームの非表示、false:全て表示 'child_of' => '53' //親タームIDを指定 ); $the_query = new WP_Term_Query($args); foreach($the_query->get_terms() as $term){ $term_link = get_term_link($term->slug,$taxonomy_slug); //タームアーカイブのリンク取得 echo '<a href="'.$term_link.'">'.$term->name.' <span>'.$term->count.'</span></a>'; } ?>
「child_of」で親タームのIDを指定します。
あとがき
WP_Term_Queryを使えば、簡単にタームの一覧を出力することができますね。