get_the_terms() の使い方|説明・引数・注意点

説明

get_the_terms() は、投稿に紐付いたターム(カスタムタクソノミー含む)を取得する関数です。

基本構文

get_the_terms( int|WP_Post $post, string $taxonomy ): WP_Term[]|false|WP_Error

引数

  • $post:投稿IDまたはオブジェクト
  • $taxonomy:タクソノミー名

戻り値

WP_Term の配列。なければ false。

使い方(サンプル)

$terms = get_the_terms( get_the_ID(), 'genre' );
if ( $terms && ! is_wp_error( $terms ) ) {
	foreach ( $terms as $t ) {
		var_dump( $t->name );
	}
}

注意点

  • 戻り値が false や WP_Error の場合があるため、必ず判定します。

実務での使いどころ

  • 投稿に付いた、カスタムタクソノミーのタームを取得するとき。
  • 投稿に付いた、タームの名前やリンクを、表示するとき。

よくあるミスと対処

  • ターム(が1つもない)のとき、空の配列ではなく false が返る。そのまま foreach に渡すと、警告になる。
  • エラー時には WP_Error が返る場合もある。
  • get_the_category() のように、カテゴリーだけに使える関数と混同している。

NG例

foreach ( get_the_terms( $post_id, 'news_cat' ) as $term ) {
	echo $term->name; // 無いと、警告になる
}

OK例

$terms = get_the_terms( $post_id, 'news_cat' );
if ( $terms && ! is_wp_error( $terms ) ) {
	foreach ( $terms as $term ) {
		echo esc_html( $term->name );
	}
}

使い分け早見表

関数 特徴
get_the_terms() キャッシュを使う。ない場合は false
wp_get_post_terms() データベースから取得。ない場合は空の配列
get_terms() 投稿を限定せず、ターム一覧を取得

関連項目

get_terms()、wp_get_post_terms()、get_the_category()

公式リファレンス:get_the_terms() | Function | WordPress Developer Resources

コメント

タイトルとURLをコピーしました