get_the_terms()


WordPress関数get_the_terms()は、指定された投稿またはカスタム投稿タイプに関連付けられたターム(カテゴリ、タグ、またはカスタムタクソノミー)を取得するために使用されます。

シンタックス

get_the_terms( int|WP_Post $post, string $taxonomy );

引数の説明

  • $post (int|WP_Post) — 投稿IDまたは投稿オブジェクト。
  • $taxonomy (string) — タクソノミースラッグ(例: category, post_tag, カスタムタクソノミースラッグ)。

返り値

  • 成功した場合はWP_Termオブジェクトの配列、失敗した場合はfalse、またはタームが関連付けられていない場合はnullを返します。

使用例

例 1: 投稿に関連付けられたカテゴリを取得

<?php
$categories = get_the_terms( get_the_ID(), 'category' );
if ( $categories && ! is_wp_error( $categories ) ) {
    foreach ( $categories as $category ) {
        echo $category->name;
    }
}
?>

例 2: 投稿タグを取得してリンクを表示

<?php
$tags = get_the_terms( get_the_ID(), 'post_tag' );
if ( $tags && ! is_wp_error( $tags ) ) {
    foreach ( $tags as $tag ) {
        echo '<a href="' . get_term_link( $tag ) . '">' . $tag->name . '</a>';
    }
}
?>

例 3: カスタムタクソノミーのタームを取得

<?php
$terms = get_the_terms( get_the_ID(), 'custom_taxonomy' );
if ( $terms && ! is_wp_error( $terms ) ) {
    foreach ( $terms as $term ) {
        echo $term->name;
    }
}
?>

例 4: 投稿に関連付けられたタームが存在するか確認

<?php
if ( get_the_terms( get_the_ID(), 'category' ) ) {
    echo 'この投稿にはカテゴリがあります。';
} else {
    echo 'カテゴリがありません。';
}
?>

例 5: 複数のタームを表示

<?php
$taxonomies = ['category', 'post_tag'];
foreach ( $taxonomies as $taxonomy ) {
    $terms = get_the_terms( get_the_ID(), $taxonomy );
    if ( $terms && ! is_wp_error( $terms ) ) {
        foreach ( $terms as $term ) {
            echo $term->name . ', ';
        }
    }
}
?>

注意点

  • 返り値がfalseまたはnullの場合を確認し、エラーを防ぎましょう。
  • カスタムタクソノミーを使用する際は、正しいスラッグを指定してください。

関連機能: