
目次
the_terms()の用途
the_terms()
は、投稿に紐づくターム(カテゴリー・タグ・カスタムタクソノミー)を直接表示する関数です。get_the_term_list()
とほぼ同じ動作ですが、こちらは返り値を取得せず即出力します。
the_terms()の構文
the_terms( int $post_id, string $taxonomy, string $before = '', string $sep = ', ', string $after = '' )
the_terms()のパラメータ
$post_id
: 投稿ID(ループ内ならget_the_ID()
)$taxonomy
: タクソノミー名(category
,post_tag
, カスタムタクソノミー)$before
: 出力の先頭に付ける文字列$sep
: タームを区切る文字列$after
: 出力の末尾に付ける文字列
the_terms()の戻り値
何も返さず直接出力します。
the_terms()の基本例
カテゴリーをカンマ区切りで表示
the_terms( get_the_ID(), 'category' );
出力例<a href="...">ニュース</a>, <a href="...">イベント</a>
the_terms()の装飾例
the_terms( get_the_ID(), 'category', '<p>カテゴリー: ', ' / ', '</p>' );
出力例<p>カテゴリー: <a href="...">ニュース</a> / <a href="...">イベント</a></p>
カスタムタクソノミー例
the_terms( get_the_ID(), 'genre', 'ジャンル: ', ', ', '' );
出力例ジャンル: <a href="...">ミステリー</a>, <a href="...">ファンタジー</a>
タームがない場合
タームが紐づいていない場合は何も表示されません。
ターム有無の確認
タームがあるときだけ表示する例
if ( get_the_terms( get_the_ID(), 'category' ) ) {
the_terms( get_the_ID(), 'category', 'カテゴリー: ', ', ', '' );
}
the_terms()の類似関数との比較
関数 | 特徴 |
---|---|
the_terms() | 直接表示 |
get_the_term_list() | 文字列を返す(表示は自分で行う) |
get_the_terms() | タームオブジェクト配列を返す |
get_the_category_list() | カテゴリー専用、文字列を返す |
get_the_tag_list() | タグ専用、文字列を返す |