Mill's Note

【Wordpress関数】get_the_terms()

/

投稿に紐づいたカテゴリーやタグ、タクソノミーを一覧(配列)で取得する、Wordpressテンプレートタグ。
戻り値を指定して、タームの様々な情報を取得・出力することができます。

投稿IDを指定することでループ外でも使用できます。

get_the_terms() 呼び出しコード

get_the_terms() は、引数のtaxonomy [ カテゴリー(‘category’)、タグ(‘post_tag’)、タクソノミー(‘タクソノミー slug’) ] を指定して、カスタムタクソノミーだけではなくカテゴリーやタグ一覧も呼び出すことができます。

呼び出しコードパラメータ説明
<?php $cats = get_the_terms(get_the_ID(),'taxonomy'); ?>投稿ID,taxonomy現在のページに紐づくターム (投稿ループ内)
<?php $cats = get_the_terms(投稿ID,'taxonomy'); ?>投稿ID,taxonomy指定した投稿に紐づくターム (ループ外)
get_the_terms() は、引数の 投稿ID、taxonomy ともに必須 。

get_the_terms() 戻り値

変数名内容
term_idintタームID
namestringターム名
slugstringタームスラッグ
parentint親タームID
countint記事数
descriptionstringターム説明
taxonomystringtaxonomy名
term_taxonomy_idint taxonomy ID
タームは、個別カテゴリー、個別タグ、カスタムタクソノミーに含まれるタームを指します

get_the_terms() の使用例

タームの情報を呼び出し、必要な戻り値を利用して出力します。

最初、又は、指定番目のtermを1件だけ取得

タームは配列で取得しますので、何番目かを[n] として指定。
配列は 0 から数えますので、最初のtermなら [0] を指定します

PHP
<?php
  $terms = get_the_terms(get_the_ID(),'taxonomy');
  /*  配列の〇番目を指定 - 例は最初のterm  */
  $name = $terms[0]->name;
  $id   = $terms[0]->term_id;
?>
<a href="<?php echo get_term_link($id, 'taxonomy'); ?>"><?php echo $name; ?></a>
<?php } ?>

紐づくtermを一覧で取得

foreach{ } で紐づいている全てのタームを出力します。

PHP
<?php
  $tax = 'taxonomy';
  $terms = get_the_terms(get_the_ID(),$tax);
  foreach ($terms as $term){
    $name = $term->name;
    $id   = $term->term_id;
?>
<a href="<?php echo get_term_link($id, $tax); ?>"><?php echo $name; ?></a>
<?php } } ?>