【wordpress】カスタム投稿でのターム(カテゴリー)の取得&出力

wordpress

※ 当サイトではアフィリエイト広告を利用しています。

こんにちは、meiです。

今回はカスタム投稿でのターム(カテゴリー)の取得方法および出力方法についてまとめたいと思います。

ループ内の場合

タームをひとつだけ表示させる場合(リンク無し)

get_the_terms()を使用し、配列で格納されている一番最初のものを出力します。

<?php
$terms = get_the_terms( $post->ID, 'タクソノミー名' );
$term_name = $terms[0]->name;   //ターム名取得
$term_slug= $terms[0]->slug; //タームスラッグ取得
?>

<div class="category">
<?php echo $term_name; ?>
</div>

タームをひとつだけ表示させる場合(リンク有り)

リンクを出力するときにはget_category_link()を使用します。

<?php
  $terms = get_the_terms( $post->ID, 'タクソノミー名');
 $term = $terms[0];
  $term_name = $term -> name;
  &term_id = $term -> term_id;
?>

<div class="category">
<a href="<?php echo get_term_link($term_id); ?>"><?php echo $term_name; ?></a>
</div>

タームを複数表示させる場合(リンク無し)

同じくget_the_terms()を使用し、配列で格納されているすべてのデータを出力します。

<?php
$terms = get_the_terms( $post->ID, 'タクソノミー名' );
if ($terms) {
	echo '<ul>';
	foreach ( $terms as $term ) {
		echo '<li>'. $term->name '</li>';
	}
	echo '</ul>';
}
?>

タームを複数表示させる場合(リンク有り)

<?php
$terms = get_the_terms( $post->ID, 'タクソノミー名' );
if ($terms) {
	echo '<ul>';
	foreach ( $terms as $term ) {
		echo '<li><a href="'.get_term_link($term ->term_id).'">'.$term ->name.'</a></li>';
	}
	echo '</ul>';
}
?>

ループ外の場合

ループ外の場合もループ内と同様get_the_termsを使えますが、引数に投稿のIDを渡す必要があります。

wordpress
スポンサーリンク
Web Parts Box
タイトルとURLをコピーしました