【WordPress】投稿のタームを取得する

get_the_terms()を利用してタームのオブジェクトを取得します。

取得したオブジェクトには、URL情報がないので、get_term_link()を利用して取得します。

<?php
$post_terms = get_the_terms( $post->ID, '[タクソノミースラッグ]' );
?>
<?php if ( $post_terms ) : ?>
	<ul>
		<?php foreach ( $post_terms as $post_term ) :
			$term_link = get_term_link( $post_term );
			?>
			<li>
				<a href="<?php echo esc_url( $term_link ); ?>"><?php echo $post_term->name; ?></a>
			</li>
		<?php endforeach; ?>
	</ul>
<?php endif; ?>

参考に、get_the_terms()で取得したオブジェクトは以下のような情報が格納されています。

array (size=1)
  0 => 
    object(WP_Term)[7182]
      public 'term_id' => int 11
      public 'name' => string 'news' (length=4)
      public 'slug' => string 'news' (length=4)
      public 'term_group' => int 0
      public 'term_taxonomy_id' => int 11
      public 'taxonomy' => string 'post_category' (length=13)
      public 'description' => string '' (length=0)
      public 'parent' => int 0
      public 'count' => int 1
      public 'filter' => string 'raw' (length=3)

参考

石井秀幸@WEBデザイナー
横浜WordPress Meetup 主宰/株式会社ノクチ基地 取締役/モンゼンクリエイティブ合同会社 代表
WEB制作に関する技術や役立つ情報を発信していきます。10年にわたるWordPress歴を背景に、幅広いアイデアを形にするお手伝いをしています。