wp_get_post_terms()


WordPressのwp_get_post_terms()関数は、指定された投稿のタクソノミーに関連付けられた用語(タグやカテゴリなど)を取得します。

構文

wp_get_post_terms( int $post_id, string $taxonomy, array $args = array() );

引数の説明

  • $post_id (int) — 投稿のIDを指定します。
  • $taxonomy (string) — 取得するタクソノミーのスラッグを指定します。
  • $args (array) — 取得時のオプションを指定します(例: orderby, order)。

例 1: 投稿のカテゴリを取得

指定した投稿のカテゴリを取得し表示します。

<?php
$terms = wp_get_post_terms( get_the_ID(), 'category' );
foreach ( $terms as $term ) {
    echo $term->name;
}
?>

例 2: 投稿のタグを取得

指定した投稿のタグを取得し、リンク付きで表示します。

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

例 3: タクソノミーに基づくカスタム投稿タイプの用語を取得

カスタム投稿タイプのタクソノミー用語を取得します。

<?php
$terms = wp_get_post_terms( get_the_ID(), 'custom_taxonomy' );
if ( ! empty( $terms ) ) {
    echo $terms[0]->name;
}
?>

例 4: 特定の順序で用語を取得

取得した用語を名前順でソートします。

<?php
$args = array( 'orderby' => 'name', 'order' => 'ASC' );
$terms = wp_get_post_terms( get_the_ID(), 'category', $args );
foreach ( $terms as $term ) {
    echo $term->name;
}
?>

例 5: 投稿に用語が関連付けられているか確認

投稿にカテゴリが関連付けられているかどうかを確認します。

<?php
$terms = wp_get_post_terms( get_the_ID(), 'category' );
if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
    echo 'この投稿にはカテゴリがあります。';
} else {
    echo 'カテゴリはありません。';
}
?>

注意事項

  • この関数は、get_the_ID()を使用することで現在の投稿のIDを自動的に取得できます。
  • wp_get_post_terms()WP_Termオブジェクトの配列を返します。

関連機能: